Testing method that uses dependency injection (structuremap)
I have got a factory method that create new instances of a certain interface.
I am using StructureMap to create 开发者_高级运维new instances of the interface.
How can I unit test this method?
If you make the factory take an IContainer as a ctor dependency you can stub out the container.
The IContainer should be resolved automatically by Structure Map if you configure Structure Map to instantiate the factory.
Edit:
I was thinking about something like this, taking Structure Map out of the equation when testing:
[Test]
public void ResolvesFooFromContainer()
{
var expectedFoo = new Foo();
var container = MockRepository.GenerateStub<IContainer>();
container.Stub(c => c.GetInstance<Foo>()).Return(foo);
var factory = new FooFactory(container);
var createdFoo = factory.CreateFoo();
Assert.That(createdFoo, Is.EqualTo(expectedFoo));
}
The example uses Rhino Mocks and NUnit, but of course you can test and stub any way you want.
I was finally able to achieve what I wanted.
If you will think about it, you want to perform your test in an isolated environment.
So I just needed to initialise structure with a mock object and I was able to test my factory method.
精彩评论