覆盖自动填充注册 - 使用DI进行集成测试 [英] Override Autofac registration - Integration tests with DI

查看:179
本文介绍了覆盖自动填充注册 - 使用DI进行集成测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的应用程序编写了集成测试,并为此使用我的容器。我想要像在实际运行中一样注册所有组件,然后覆盖一些组件并将其切换为使用存根实现。

I write integration tests for my application, and use my container for this. I want to be able to register all the components as I do in real running, and then override some of the components and switch them to use stubs implementations.

我不想分离DI,并且只有测试一个真正的东西才有容器用于测试。

I wouldn't want to seperate the DI and have a container for tests only because I want to test the real thing.

这样做似乎也很丑:

public class MyRegistrations
{
     public static RegisterAll(bool isInTest= false)
     {
           if (isTest) 
           {
             // Register test fakes
            }
            else
                  // Register real components
      }
}



So I thought of overriding registrations in my test enviorment. How should it be done?

任何其他更好的方式来实现我的目标?

Any other better ways for achieving my goal?

谢谢

推荐答案


Autofac将使用最后注册的组件作为该服务的默认提供者

Autofac will use the last registered component as the default provider of that service

从AutoFac文档

在你的排列/ setup / testInit阶段注册mocks,然后解析SUT:

In your arrange/setup/testInit phase register the mocks, then resolve the SUT:

[SetUp]
public void TestInit()
{
    Mock<IFoo> mock = new Mock<IFoo>();
    builder.RegisterInstance(mock.object).As<IFoo>();
    ...
    ...
    _target = builder.Resolve<The component>();
}

注意:

单身人士,静态成员和SingletonLifestyle(注册)可能会导致一些麻烦....

Singletons, static members and SingletonLifestyle(registration) may cause some troubles....

这篇关于覆盖自动填充注册 - 使用DI进行集成测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆