Mock objects

An often used technique within unit testing is mocking of objects. Mocking means that you create an instance of an object, which responds exactly as you want. This comes in really handy when you for example want to unit test a piece of code which interacts with some piece of hardware. By simply mocking the hardware you can “simulate” the hardware in order to test your code which access this hardware.
NUnit has by default a framework for mocking objects. This framework is also used by unit testing the nunit framework. When you have an interface and don’t need to implement all methods which are available within this interface, you can simply create a mock object from this interface by using “DynamicMock” within the NUnit framework:
DynamicMock myExampleMock = new DynamicMock(typeof(IMyExample)); // Creates a mock object from the defined interface
myExampleMock.ExpectAndReturn(“AmethodName”, // the method name
“abc” // return value
Null  // expected arguments);
IMyExample myExampleInstance = (IMyExample)securityTokenServiceMock.MockInstance;
This will create an instance of an object which implements the given interface. With the “ExpectAndReturn” you can define methods on your mockup and implement how they will react on performed method operations. For example in the example above, when you call “AmethodName” on your myExampleInstance, the string “abc” will be returned.
To use the mockup framework, beside adding the nunit.framework.dll, you also have to add the nunit.mock.dll assembly to your project.
Posted in C#, TDD at July 2nd, 2012. 1 Comment.