简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM