Best practices for unit tests, mock objects and ioc

Ok, that's why I tried to get into IoC lately. However, I continue to encounter one obstacle - that I like to use the layout of objects.

They set up quickly and painlessly.

However, if I use IoC all over the place in my code, it forces me to create test implementations (and configurations) of my objects instead of using layouts (i.e. using moq).

As a result, I get huge configuration files for testing.

In addition, there are many testing scenarios in which I require different behaviors from my classes on a test basis. With moq objects, this is very simple. How will you do something similar with IoC?

Any help would be greatly appreciated.

Thanks
Mike

+5
source share
2 answers

IoC should make it easier to work with mock objects, not harder.

Several IoC Container frameworks allow you to define pre-existing objects for injection; with Moq, you just set it for myMockObject.Object.

EDIT: An example of setting up Unity using a layout:

var mockService = new Mock<IMyService>();
container.RegisterInstance<IMyService>(mockService.Object);

Alternatively, you can simply pass the mock object to the constructor of the test class (to inject the constructor) and completely bypass the IoC container in your unit tests.

EDIT: Josh's answer is a good example of an alternative. I would usually go with his solution, and not reconfigure the container.

+5
source

IoC, Mock Objects...

. - , , , SUT.

[Test]
public void AnAwesomeTest()
{
    IDependencyOne d1 = MyMocker.Create<IDependencyOne>();
    IDependencyTwo d2 = MyMocker.Create<IDependencyTwo>();

    //Constructor injection
    SUT sut = new SUT(d1);

    //Property Injection
    sut.DependantProperty = d2;

    //Do some stuff and Assert
}
+3

All Articles