使用 IoC 进行单元测试 [英] Using IoC for Unit Testing

查看:50
本文介绍了使用 IoC 进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

一般来说,DI Container 不应该是单元测试所必需的,因为单元测试就是为了分离职责.

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

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

Consider a class that uses Constructor Injection

public MyClass(IMyDependency dep) { }

在您的整个应用程序中,IMyDependency 后面可能隐藏着一个巨大的依赖关系图,但是在单元测试中,您将其压平为一个 测试替身.

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.

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

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

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

在某些情况下,自动模拟容器可以很高兴拥有,但您不需要使用与生产应用程序相同的 DI 容器.

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

这篇关于使用 IoC 进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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