覆盖IOC注册以用于集成测试 [英] Overriding IOC Registration for use with Integration Testing

查看:84
本文介绍了覆盖IOC注册以用于集成测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想我可能不太了解您将如何使用IOC容器进行集成测试.

so I think I'm perhaps not fully understanding how you would use an IOC container for doing Integration tests.

假设我有几节课:

public class EmailComposer : IComposer
{
    public EmailComposer(IEmailFormatter formatter)
    {
        ...
    }
    ...
    public string Write(string message)
    {
        ...
        return _formatter.Format(message);
    }
}

好的,因此可以在实际应用程序中使用(我在这里使用autofac),我将创建一个模块并执行以下操作:

OK so for use during the real application (I'm using autofac here) I'd create a module and do something like:

    protected override void Load(ContainerBuilder containerBuilder)
    {
        containerBuilder.RegisterType<HtmlEmailFormatter>().As<IEmailFormatter>();
    }

表现出完美的感觉并表现出色.

Makes perfect sense and works great.

当涉及到单元测试时,我根本不会使用IOC容器,而只是在进行测试时模拟出格式化程序.再次很棒.

When it comes to Unit Tests I wouldn't use the IOC container at all and would just mock out the formatter when I'm doing my tests. Again works great.

现在就我的集成测试而言... 理想情况下,显然,我将在集成测试期间运行整个堆栈,但是让我们假装HtmlEmailFormatter是一些速度较慢的外部WebService,因此我决定使用Test Double符合我的最大利益. 但是...我不想在所有集成测试中都使用Test Double,只是一个子集(一组可以快速运行的冒烟测试风格的测试).

OK now when it comes to my integration tests... Ideally I'd be running the full stack during integration tests obviously, but let's pretend the HtmlEmailFormatter is some slow external WebService so I decide it's in my best interest to use a Test Double instead. But... I don't want to use the Test Double on all of my integration tests, just a subset (a set of smoke-test style tests that are quick to run).

这时,我想注入模拟版本的Web服务,以便可以验证仍然在其上调用了正确的方法.

At this point I want to inject a mock version of the webservice, so that I can validate the correct methods were still called on it.

所以,真正的问题是:

如果我有一个带有带有多个参数的构造函数的类,那么如何使其中一个参数解析为对象的实例(即正确设置的Mock),而其余的则由autofac填充?

推荐答案

我会说您为此使用了SetUp和TearDown(NUnit)或ClassInitialize和ClassCleanup(MSTest).在初始化时,您注册临时测试类,在清理中,您恢复到正常状态.

I would say you use the SetUp and TearDown (NUnit) or ClassInitialize and ClassCleanup (MSTest) for this. In initialize you register your temporary test class and in cleanup you restore to normal state.

让DI容器为您指定所有依赖项的好处是,可以解决依赖项的整个对象图.但是,如果只有一个测试要使用其他实现,则可以使用Mocking框架.

Having the DI container specify all the dependencies for you has the benefit of getting an entire object graph of dependencies resolved. However if there's a single test in which you want to use a different implementation I would use a Mocking framework instead.

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

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