How can a IoC Container be used for unit testing? Is it useful to manage mocks in a huge solution (50+ projects) using IoC? Any experiences? Any C# libraries that work well
I often use an IoC container in my tests. Granted, they are not "unit tests" in the pure sense. IMO They are more BDDish and facilitate refactoring. Tests are there to give you confidence to refactor. Poorly written tests can be like pouring cement into your code.
Consider the following:
[TestFixture]
public class ImageGalleryFixture : ContainerWiredFixture
{
[Test]
public void Should_save_image()
{
container.ConfigureMockFor()
.Setup(r => r.Create(It.IsAny()))
.Verifiable();
AddToGallery(new RequestWithRealFile());
container.VerifyMockFor();
}
private void AddToGallery(AddBusinessImage request)
{
container.Resolve().Consume(request);
}
}
There are several things that happen when adding an image to the gallery. The image is resized, a thumbnail is generated, and the files are stored on AmazonS3. By using a container I can more easily isolate just the behavior I want to test, which in this case is the persisting part.
An auto-mocking container extension comes in handy when using this technique: http://www.agileatwork.com/auto-mocking-unity-container-extension/