Unit tests should not use the container at all. Dependency Injection (DI) comes in two phases:
- Use DI patterns to inject dependencies into consumers. You don't need a container to do that.
- At the application's Composition Root, use a DI Container (or Poor Man's DI) to wire all components together.
How not to use any DI Container at all for unit testing
As an example, consider a class that uses IRepository1. By using the Constructor Injection pattern, we can make the dependency an invariant of the class.
public class SomeClass
{
private readonly IRepository1 repository;
public SomeClass(IRepository1 repository)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
this.repository = repository;
}
// More members...
}
Notice that the readonly
keyword combined with the Guard Clause guarantees that the repository
field isn't null if the instance was successfully instantiated.
You don't need a container to create a new instance of MyClass. You can do that directly from a unit test using Moq or another Test Double:
[TestMethod]
public void Test6()
{
var repStub = new Mock<IRepository1>();
var sut = new SomeClass(repStub.Object);
// The rest of the test...
}
See here for more information...
How to use Unity for unit testing
However, if you absolutely must use Unity in your tests, you can create the container and use the RegisterInstance method:
[TestMethod]
public void Test7()
{
var repMock = new Mock<IRepository1>();
var container = new UnityContainer();
container.RegisterInstance<IRepository1>(repMock.Object);
var sut = container.Resolve<SomeClass>();
// The rest of the test...
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…