FakeItEasy and Partial Mocking

By | April 27, 2015

There are many situations where you want to partially mock the class. You typically want to change the behavior of a single method in a class having many methods. So what you do is partial mocking. FakeItEasy and Partial Mocking go very well together.

Note: FakeItEasy will not touch the method if it is not virtual. If there is a work around it then please let me know in comments.

Steps:
1 – Make the method virtual.

2- Create the fake object. Thing to understand is that this method implementation will never be invoked when the method is called on the fake. You HAVE to provide the configuration to FakeItEasy to tell it what should happen when the method is called on the fake.

Sample always helps:

var fakeSerialPort = A.Fake<fakePort>();
A.CallTo(() => fakeSerialPort.Open()).Throws(new IOException());
A.CallTo(() => fakeSerialPort.ReadTo(A.Ignored)).CallsBaseMethod();

In this sample, the first line creates a Fake.

Second line tells FakeItEasy to make the method Open throw an Exception when the method is called on the fake object.

Third line?

FakeItEasy wants the methods whose behavior you want to change in testing be virtual. It has an undesirable effect. Suppose over the course of testing you will change the behavior of two methods. One in first test and other in second test. So you make them both virtual. In first test itself there will be a problem. First method will return whatever you have configured the FakeIteasy to return. But for second method, if it gets called too, its implementation will not be used. It is virtual and hence FakeItEasy will not call on its implementation when call is made. The way out is “CallsBaseMethod” which will make sure that the base implementation is called.

I will make it clear that I am not advocating any approach. Lot of people are very strict what should be executed in a unit test. And I respect that. It is just that if you end up in this situation, I feel that you should know your options.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.