我有一个测试类,其中包含一个需要IService的构造函数。
public class ConsumerTests
{
private readonly IService _service;
public ConsumerTests(IService servie)
{
_service = service;
}
[Fact]
public void Should_()
{
//use _service
}
}
我想插入我选择的DI容器来构建测试类。
这可能与xUnit一起使用吗?
有一种方法可以使用此源代码中的nuget包执行此操作:https://github.com/dennisroche/xunit.ioc.autofac
只要你使用[Fact]
它就会很好用,但是当我开始使用[Theory]
时我被阻止了。有一个拉取请求来解决这个问题。
为了解锁我自己,我使用CollectionFixture注入Container,并从容器中解析接口。
你想测试什么? IService
的实施还是DI容器的接线?
如果您正在测试IService
实现,您应该直接在测试中实例化它们(并模拟任何依赖项):
var service = new MyServiceImplementation(mockDependency1, mockDependency2, ...);
// execute service and do your asserts, probably checking mocks
如果您正在尝试测试DI容器的接线,则需要伸出并明确地抓取已配置的容器。没有“组合根”可以为你做这些(伪代码跟随,Autofac风格):
var myContainer = myCompositionRoot.GetContainer();
var service = myContainer.ResolveCompnent<IService>();
// execute service and do your asserts with the actual implementation
如果您正在使用xUnit来运行集成测试,您需要在多个测试中使用相同的对象,请查看Fixtures:http://xunit.github.io/docs/shared-context.html。