使用Isolate.Fake.AllInstance<>()创建单独的伪造对象

时间:2018-01-30 09:36:34

标签: c# unit-testing typemock typemock-isolator

我有一个Student班级和一个Course班级:

public class Student
{
    public Student()
    {
        courses = Enumerable.Range(0, 3).Select(i => new Course { Grade = random.Next(0, 100) }).ToList();
    }
    private static Random random = new Random();

    public List<Course> courses { get; } 

    public void StudentTestMethod() => courses.ForEach(course => course.CourseMethod());
}

public class Course
{
    public int Grade { get; set; }

    public void CourseMethod() => Console.WriteLine(string.Format("Not Faked, grade = {0}", Grade));
}

Student的构造函数上,我们创建3个Course个对象并随机设置成绩。 我有以下单元测试:

public void TestMethod1()
{ 
    var fake = Isolate.Fake.AllInstances<Course>();
    Isolate.WhenCalled(() => fake.CourseMethod()).DoInstead(c =>
    {
        Console.WriteLine(string.Format("Faked, grade = {0}", fake.Grade));
    });
    Enumerable.Range(0, 5).ToList().ForEach(i =>
    {
        new Student().StudentTestMethod();
    });
}

我试图伪造Course的所有实例,以便每个学生都有3个不同的成绩,但我得到的输出是,例如:

Faked = 27 Faked = 27 Faked = 27, Faked = 44 Faked = 44 Faked = 44, Faked = 11
Faked = 11 Faked = 11, Faked = 62 Faked = 62 Faked = 62, Faked = 52 Faked = 52
Faked = 52.

关于如何让每个学生使用Typemock Isolator获得3个不同等级的任何想法?

1 个答案:

答案 0 :(得分:1)

您可以像这样编写测试:

    public void TestMethod()
    {
        List<Course> CourseList = new List<Course>();
        Enumerable.Range(0, 5).ToList().ForEach(i =>
        {

            Enumerable.Range(0, 3).ToList().ForEach(j =>
            {
                var fake = Isolate.Fake.NextInstance<Course>();
                Isolate.WhenCalled(() => fake.CourseMethod()).DoInstead(c =>
                {
                    Console.WriteLine(string.Format("Faked = {0}", fake.Grade));
                });
                CourseList.Add(fake);
            }

            );
            new Student().StudentTestMethod();

        });

    }