5 c# integration-testing unit-testing dependency-injection autofac
我为我的应用程序编写集成测试,并使用我的容器.我希望能够像在实际运行中那样注册所有组件,然后覆盖一些组件并将它们切换为使用存根实现.
我不想分开DI并且只有一个容器用于测试,因为我想测试真实的东西.
这样做看起来也很难看:
public class MyRegistrations
{
public static RegisterAll(bool isInTest= false)
{
if (isTest)
{
// Register test fakes
}
else
// Register real components
}
}
Run Code Online (Sandbox Code Playgroud)
所以我想在我的测试环境中覆盖注册.应该怎么做?
有没有更好的方法来实现我的目标?
谢谢
Autofac 将使用最后注册的组件作为该服务的默认提供者
在排列/设置/测试初始化阶段注册模拟,然后解析 SUT:
[SetUp]
public void TestInit()
{
Mock<IFoo> mock = new Mock<IFoo>();
builder.RegisterInstance(mock.object).As<IFoo>();
...
...
_target = builder.Resolve<The component>();
}
Run Code Online (Sandbox Code Playgroud)
笔记:
Singleton、静态成员和 SingletonLifestyle(注册)可能会引起一些麻烦......
| 归档时间: |
|
| 查看次数: |
2334 次 |
| 最近记录: |