Handling Constructors And Passing Arguments


There are times when you want to create the fake instance and use the real class constructor, you can do that by using
IFaker.Instance<T>() overload that accepts three arguments:
Example - fake all methods except the constructor and pass the constructor specific arguments:
public class Person
{
    public int _age;
    public string _name;

    public Person(int age, string name)
    {
        _age = age;
        _name = name;
    }
   
    // other class methods ...
}

[TestMethod, Isolated]
public void PassArgumentsToConstructor_FakeMethods()
{
    // The constructor is not faked here.
    // We are passing to the caonstructor the arguments 100, "Foo"   
1   var fake = Isolate.Fake.Instance<Person>(Members.ReturnRecursiveFakes, ConstructorWillBe.Called, 100,
                                                  "Foo");  
    Isolate.Swap.NextInstance<Person>().With(fake);

2   Person person = new Person(50, "Bar");

3   Assert.AreEqual(100, fake._age);
    Assert.AreEqual("Foo", fake._name);
}

1  We state here that we want to fake all methods except the constructor. The constructor will get the arguments 100 and "Foo".

2  The real constructor is called with our custom arguments - 100 and "Foo"

3  Asserting that the arguments sent to the constructor.

We can also use the second argument of IFaker.Instance<T>() to state that we want to call all original methods while ignoring the constructor.
Example:
[TestMethod, Isolated]
public void FakeTheConstructor_CallOriginalMethods()
{
    // Call original methods but fake the constructor.
1   var fake = Isolate.Fake.Instance<Person>(Members.CallOriginal, ConstructorWillBe.Ignored);

2   Assert.AreEqual(0, fake._age);
    Assert.IsNull(fake._name);
}

1  We state here that we want all original methods to be called by using Members.CallOriginal and that the constructor should be ignored by using ConstructorWillBe.Ignored

2  Asserting that the constructor is not called.

 When not using the ConstructorWillBe enum the default behavior for constructor is using the following rules:

Copyright © Typemock Ltd. 2004-2010. All Rights Reserved.