Susbtitute behaviour of a method call in constructor with typemock

237 Views Asked by At

So I am asked to test this constructor call.

public class testClass
{
  private bool keyValue = 45;
  public testClass()
  {
    MethodOne();

    keyValue = 900;
    MethodTwo();
    MethodThree();
    keyValue = 221;
  }
}

In the code above, keyValue(global field) is constantly being set. The methods use keyValue in each decision making algorithm. I want to assert that keyValue is set to this value.

Getting the current values of fields is possible by using

Isolate.whenCalled(() => obj.MethodOne())
.DoInstead(context => 
{
   testClass object = (testClass)context.Instance;
   // from here on, get any fields
}); 

I find that the code above could only be done anywhere except for the constructor.(correct me if I am wrong)

Another point is that I could only mock methods before the constructor is ran only by using the MockManager API.

[Test]
public void testMethod()
{
    Mock mockObj = MockManager.Mock(typeof(testClass));
    mockObj.ExpectCall("MethodOne");

    //instantiate tested object 
    testClass testedObj = new testClass();
}

Although the code above asserts that MethodOne() is called in the constructor, I could not alter its behaviour to check the fields.

Any enlightment/ help would really help.Thanks in advance.

1

There are 1 best solutions below

0
Gregory Prescott On

If I understood you correctly:

I want to assert that keyValue is set to this value

a relevant test would be:

[TestMethod]
public void TestMethod1()
{
    // Fake the object, Ignore calls, Invoke original ctor
    testClass tc = Isolate.Fake.Instance<testClass>(Members.ReturnNulls, ConstructorWillBe.Called);

    // Create a getter for keyValue and call it's original implementation
    Isolate.WhenCalled(() => tc.KeyVal).CallOriginal();

    // Assert that by the end of the ctor keyValue is equal to 221
    Assert.AreEqual(221, tc.KeyVal); 
}

Is this what you had in mind?