我为我的应用程序编写集成测试,并为此使用我的容器。我希望能够像在实际运行中那样注册所有组件,然后覆盖一些组件并将它们切换为使用 stub 实现。
我不想分离 DI 并拥有一个用于测试的容器,只是因为我想测试真实的东西。
这样做也很丑陋:
public class MyRegistrations
{
public static RegisterAll(bool isInTest= false)
{
if (isTest)
{
// Register test fakes
}
else
// Register real components
}
}
所以我想到了在我的测试环境中覆盖注册。应该怎么做?
还有其他更好的方法来实现我的目标吗?
谢谢
最佳答案
Autofac will use the last registered component as the default provider of that service
在您的 arrange/setup/testInit 阶段注册模拟,然后解析 SUT:
[SetUp]
public void TestInit()
{
Mock<IFoo> mock = new Mock<IFoo>();
builder.RegisterInstance(mock.object).As<IFoo>();
...
...
_target = builder.Resolve<The component>();
}
注意:
Singletons, static members 和 SingletonLifestyle(registration) 可能会引起一些麻烦....
关于c# - 覆盖 Autofac 注册 - 使用 DI 进行集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36470772/