Wednesday, November 18, 2009 9:36 PM
Sean Feldman
StructureMap & Mocking
I really like working with StructureMap. Today I had to write a quick Factory that would leverage StructureMap to create returned instances. The Factory would look like this:
public class HttpListenerFactory : IHttpListenerFactory
{
private readonly IConfigurationManager configurationManager;
public HttpListenerFactory(IConfigurationManager configurationManager)
{
this.configurationManager = configurationManager;
}
public ICustomHttpListener CreateListenerForMessagesComingFromX()
{
var listener = ObjectFactory.GetInstance<ICustomHttpListener>();
listener.Prefix = configurationManager.GetListenerPrefixForMessagesComingFromX();
return listener;
}
public ICustomHttpListener CreateListenerForMessagesComingFromY()
{
var listener = ObjectFactory.GetInstance<ICustomHttpListener>();
listener.Prefix = configurationManager.GetListenerPrefixForMessagesComingFromY();
return listener;
}
}
Factory has no parameterized constructor and it’s heavily relies on ObjectFactory provided by StructureMap.
I wanted during testing to keep it as a spec (unit test) and not integration test, heaving all interfaces and implementers hooked up, so bootstrapping StructureMap was not an option. What I could do, is inject mocked implementation in conjunction with the interface. That worked really slick.
protected readonly Mock<ICustomHttpListener> listener;
// Arrangement stage
ObjectFactory.Inject(typeof(ICustomHttpListener), listener.Object);
// Tear down stage
ObjectFactory.ResetDefaults();
Clean and simple.
Filed under: TDD