C# 使用 IoC 进行单元测试

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1465849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 17:50:15  来源:igfitidea点击:

Using IoC for Unit Testing

c#unit-testingmockinginversion-of-control

提问by crauscher

How can a IoC Container be used for unit testing? Is it useful to manage mocks in a huge solution (50+ projects) using IoC? Any experiences? Any C# libraries that work well for using it in unit tests?

IoC 容器如何用于单元测试?使用 IoC 在大型解决方案(50 多个项目)中管理模拟有用吗?有什么经验吗?任何 C# 库都可以很好地在单元测试中使用它?

采纳答案by Mark Seemann

Generally speaking, a DI Container should not be necessary for unit testing because unit testing is all about separating responsibilities.

一般来说,单元测试不需要 DI 容器,因为单元测试就是分离职责。

Consider a class that uses Constructor Injection

考虑一个使用构造函数注入的类

public MyClass(IMyDependency dep) { }

In your entire application, it may be that there's a huge dependency graph hidden behind IMyDependency, but in a unit test, you flatten it all down to a single Test Double.

在您的整个应用程序中,可能有一个巨大的依赖图隐藏在 后面IMyDependency,但在单元测试中,您将其全部压缩为单个Test Double

You can use dynamic mocks like Moq or RhinoMocks to generate the Test Double, but it is not required.

您可以使用 Moq 或 RhinoMocks 等动态模拟来生成测试替身,但这不是必需的。

var dep = new Mock<IMyDependency>().Object;
var sut = new MyClass(dep);

In some cases, an auto-mocking containercan be nice to have, but you don't need to use the same DI Container that the production application uses.

在某些情况下,自动模拟容器可能很好,但您不需要使用与生产应用程序相同的 DI 容器。

回答by Pascal Thivent

How can a Ioc Container be used for unit testing?

如何使用 Ioc Container 进行单元测试?

IoC will enforce programming paradigms that will make unit testing in isolation (i.e. using mocks) easier: use of interfaces, no new(), no singletons...

IoC 将强制执行编程范式,使孤立的单元测试(即使用模拟)更容易:使用接口,没有 new(),没有单例……

But using the IoC container for testing is not really a requirement, it will just provide some facilities e.g. injection of mocks but you could do it manually.

但是使用 IoC 容器进行测试并不是真正的要求,它只会提供一些工具,例如注入模拟,但您可以手动完成。

Is it useful to manage mocks in a huge solution (50+ projects) using IoC?

使用 IoC 在大型解决方案(50 多个项目)中管理模拟有用吗?

I'm not sure what you mean by managing mocks using IoC. Anyway, IoC containers can usually do more than just injecting mocks when it comes to testing. And if you have decent IDE support that makes refactoring possible, why not using it?

我不确定使用 IoC 管理模拟是什么意思。无论如何,在测试方面,IoC 容器通常可以做的不仅仅是注入模拟。如果您有不错的 IDE 支持使重构成为可能,为什么不使用它呢?

Any experience?

有什么经验吗?

Yes, on a huge solution, you need more than ever a non error-prone and refactoring-adverse solution (i.e. either through a type safe IoC container or good IDE support).

是的,在一个庞大的解决方案中,您比以往任何时候都更需要一个不易出错且不利于重构的解决方案(即通过类型安全的 IoC 容器或良好的 IDE 支持)。

回答by Mike Valenty

I often use an IoC container in my tests. Granted, they are not "unit tests" in the pure sense. IMO They are more BDDish and facilitate refactoring. Tests are there to give you confidence to refactor. Poorly written tests can be like pouring cement into your code.

我经常在测试中使用 IoC 容器。当然,它们不是纯粹意义上的“单元测试”。IMO 他们更 BDDish 并促进重构。测试是为了让您有信心进行重构。写得不好的测试就像往你的代码里浇水泥一样。

Consider the following:

考虑以下:

[TestFixture]
public class ImageGalleryFixture : ContainerWiredFixture
{
    [Test]
    public void Should_save_image()
    {
        container.ConfigureMockFor<IFileRepository>()
            .Setup(r => r.Create(It.IsAny<IFile>()))
            .Verifiable();

        AddToGallery(new RequestWithRealFile());

        container.VerifyMockFor<IFileRepository>();
    }

    private void AddToGallery(AddBusinessImage request)
    {
        container.Resolve<BusinessPublisher>().Consume(request);
    }
}

There are several things that happen when adding an image to the gallery. The image is resized, a thumbnail is generated, and the files are stored on AmazonS3. By using a container I can more easily isolate just the behavior I want to test, which in this case is the persisting part.

将图像添加到图库时会发生多种情况。调整图像大小,生成缩略图,并将文件存储在 AmazonS3 上。通过使用容器,我可以更轻松地隔离我想要测试的行为,在这种情况下,它是持久性部分。

An auto-mocking container extension comes in handy when using this technique: http://www.agileatwork.com/auto-mocking-unity-container-extension/

使用此技术时,自动模拟容器扩展会派上用场:http: //www.agileatwork.com/auto-mocking-unity-container-extension/

回答by dadhi

Using containers with ability to resolve unregistered/uknown services like SimpleInjector, DryIoc(its mine) can return mocks for not yet implemented interfaces.

使用具有解析未注册/未知服务(如SimpleInjector )能力的容器,DryIoc(它的我的)可以为尚未实现的接口返回模拟

Which means that you can start development with first simple implementation and its mocked dependencies, and replace them with real thing as you progress.

这意味着您可以从第一个简单的实现及其模拟的依赖项开始开发,并随着您的进展将它们替换为真实的东西。