Search code examples
c#tddtypemock

bypass dispose for testing


I'm trying to test a method. I want to ensrur that there is a method call in that method (calling service) the code look like this:

using(proxy = new Proxy())
{ 
      proxy.CallService();
}

I swap the proxy with fake object (using TypeMock) but get error because of the fake object disposed in the end of block. I don't want to remove that "using" block. Thanks


Solution

  • Disclaimer: I work at Typemock
    If you are using the Arrange Act Assert API you can use Members.ReturnRecursiveFakes when you are creating your fake object (Note: this is the default from version 5.2.0) This will automatically fake the Dispose method as well.

    so your test will be something like this:

    var fake = Isolate.Fake.Instance<Proxy>(Members.ReturnRecursiveFakes);
    Isolate.WhenCalled(() => fake.CallService()).IgnoreCall();
    Isolate.Swap.NextInstance<Proxy>().With(fake);
    
    UnderTest classUnderTest = new ClassUnderTest();
    classUnderTest.MethodUnderTest(); // assuming the Proxy instance is used here.
    
    Isolate.Verify.WasCalledWithAnyArguments(()=>fake.CallService());
    

    I want to add to what Jon Skeet said that I would create a separate test that will ensure that the Dispose method is called.
    I think it is a good practice to assert one thing in each test method, that way when a test breaks up you'll know the reason immediately.