May
16
Written by:
brettright
Sunday, May 16, 2010 4:03 PM
When Doing TDD you are trying to Isolate your SUT (System Under Test). To do this you typically create Test Doubles (see previous blog) either automatically with a tool such as RhinoMocks or manually (i.e. you hand code the TestDouble).
When testing complex logic typically in the Logic/Services Layer you land up a significant number of your test doubles being simple Stubs (i.e. they are there to fulfill a parameter list or are being used inside the method but are of no interest to this particular test).
In these cases I typically use RhinoMocks (the new RhinoMocks is awesome) to create my Stubs. The problem is that I then have to register my Proxy Stubs with the IOC Container so that the Resolve works. This is just another overhead with testing. I am a firm believer in making testing as frictionless as possible.
Enter the AutoMockingUnityContainer
Well the AutoMockingUnityContainer turned out to be the simplist thing on earth to write even easier than the AutoResolvingUnityContainer.
The code consists of catching the ResolutionFailedException and then returning a Stub from RhinoMocks.
public override object Resolve(Type t, string name)
{
try
{
return base.Resolve(t, name);
}
catch (ResolutionFailedException)
{
//Debug.WriteLine(string.Format("AutoMocking - Reolved type:{0}", t));
return MockRepository.GenerateStub(t, null);
}
}
This code assumes that the object you are trying to create a stub for has a null constructor if this is not the case then you will need to create the Stub Manually and register it with your IOC Container. Or you could improve this Class to resolve constructors recursively.
DOWNLOAD THIS FOR FULL SOURCE WITH TESTS
AutoResolvingUnityContainer.zip