HilaB
HilaB

Reputation: 179

Creating separated faked objects using Isolate.Fake.AllInstance<>()

I have a Student class and a Course class:

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));
}

On the constructor of Student, we create 3 Course objects and set the grades randomly. I have the following unit test:

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();
    });
}

I'm trying to fake all instances of Course, so that each student will have 3 different grades, but the output I get is, for example:

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.

Any ideas on how I can make each student have 3 different grades using Typemock Isolator?

Upvotes: 1

Views: 359

Answers (1)

JamesR
JamesR

Reputation: 745

You can write your test like this:

    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();

        });

    }

Upvotes: 1

Related Questions