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
85 void MyMethod(string name);
88 public class MyExampleClass
90 public IMyInterface MyPropertyOne
96 public IMyInterface MyPropertyTwo
102 public IMyInterface MyPropertyThree
108 public MyExampleClass()
115 public class MyExampleClassTest
117 private MyExampleClass _myExampleClass;
118 private Mockery _mocks;
121 public void Init()
123 _myExampleClass = new MyExampleClass();
124 _mocks = new Mockery();
126 //This call fills all the three properties with mocks
129 //This call fills only MyPropertyOne and MyPropertyTwo with mocks
130 _mocks.FillWithMocks(_myExampleClass, “MyPropertyOne”, “MyPropertyTwo”);
Comments are welcome!