c# - 覆盖 Autofac 注册 - 使用 DI 进行集成测试

标签 c# unit-testing dependency-injection integration-testing autofac

我为我的应用程序编写集成测试,并为此使用我的容器。我希望能够像在实际运行中那样注册所有组件,然后覆盖一些组件并将它们切换为使用 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

From the AutoFac documation.

在您的 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/

相关文章:

C#:图表:从收到的 UDP 数据包中放入数据的最快方法

java - JUnit 和 Clojure 单元测试

ios - Swift - 闭合模式

java - 命名约定 JUnit 后缀或前缀 Test

c# - 保持源代码关闭,单元测试更接近

c# - 带有附加依赖的简单注入(inject)器装饰

java - Spring组件对一个字段的多个实现的依赖注入(inject)

c# - 如何在调试中隐藏 xaml ui 元素

c# - 如果十进制参数的精度错误,查询速度会变慢

c# - 通知编译器变量可能从另一个线程更新