TypeMock Isolation Members - CallOriginal
This post assumes you are familiar with TypeMock's Arrange-Act-Assert method of test creation. If you are not, please read my overview at: http://dotnetslackers.com/articles/designpatterns/TypeMocks-Arrange-Act-Assert.aspx.
When creating your fakes with TypeMock, you have to be careful which member your choose as the default mocking level. For instance, when you create the following class:
var cls = Isolate.Fake.Instance<TestClass>();
The variable cls has a fake reference to our test class. All calls to any method are mocked (no code actually runs for that method), unless you do:
Isolate.WhenCalled(() => cls.MyMethod()).CallOriginal();
You can also control the results through the other methods available from Isolate.WhenCalled, such as using WillReturn to return a pre-specified value. That is out of scope, but a good subject for a future blog post. Anyway, back to the subject, you may wonder why certain methods fail, especially if you use Isolate.Verify to verify method calls. I had the same issue, and it turns out its because of the default behavior of the fake. For instance, if I would have done:
var cls = Isolate.Fake.Instance<TestClass>(Members.CallOriginal);
The default behavior is to call the original instance of methods within the class, and not to mock their calls. This was the solution to an issue was having; I had an internal collection of objects like:
private ACollection AList
if (_aList == null)
_aList = new ACollection();
Because I didn't do the following statement during the default level of mocking access:
AList was mocked in my test and my test failed. Adding Members.CallOriginal caused AList original implementation to be called, and then the test succeeded.