Sohan's Blog

Living the Developer's Life

Unit Testing Using Mocks - FillWithMocks, Fill All or Only Selected Properties With Mocks Using Only a Single Method Call

I have been doing TDD for about two years now and using mock testing for interaction based unit testing in my projects. What I have learned over this time is, a unit testable design leads to introduction of interfaces and dependency injection for testing a code in isolation. And when I want to perform tests on my interactions, I need to create mock objects and inject these mock instances to my object under test. Sometimes, a unit test class needs to create quite a few of such mock objects and I feel this can be done using a simple wrapper around the usual mocking frameworks.

I suggest a similar and even more powerful wrapper so that you don’t need to create instances for each of the mock objects, rather do it in a single call for all your desired mocks. I have shown this method for NMock2, however, its evident that you can write your own method for your favorite mocking framework just using this code as a reference.

This code is written in C# 3.0 and should compile in .Net 3.5. You will need to add a reference to NMock2 to compile this. Also, you need to know a bit about Reflection to understand the following code fragment.

Disclaimer: This code is just a simple example and it may not suit all your needs.

83 public interface IMyInterface

84 {

85 void MyMethod(string name);

86 }


88 public class MyExampleClass

89 {

90 public IMyInterface MyPropertyOne

91 {

92 get;

93 set;

94 }


96 public IMyInterface MyPropertyTwo

97 {

98 get;

99 set;

100 }


102 public IMyInterface MyPropertyThree

103 {

104 get;

105 set;

106 }


108 public MyExampleClass()

109 {


111 }

112 }


114 [TestFixture]

115 public class MyExampleClassTest

116 {

117 private MyExampleClass _myExampleClass;

118 private Mockery _mocks;


120 [SetUp]

121 public void Init()

122 {

123 _myExampleClass = new MyExampleClass();

124 _mocks = new Mockery();


126 //This call fills all the three properties with mocks

127 _mocks.FillWithMocks(_myExampleClass);


129 //This call fills only MyPropertyOne and MyPropertyTwo with mocks

130 _mocks.FillWithMocks(_myExampleClass, “MyPropertyOne”, “MyPropertyTwo”);

131 }

132 }

Comments are welcome!