【发布时间】:2013-11-07 01:09:57
【问题描述】:
对依赖注入和单元测试有点新意。
为什么部分:
有一些 dll:
- MyApp.Services.Common.dll
- MyApp.Services.ProductA.dll -> 具有 ISomeDependency 及其实现
- MyApp.Services.ProductB.dll -> 具有 IOtherDependency 及其实现
- MyApp.Presentation.WindowsService.dll
WindowsService 仅引用 Common.dll 以使测试、版本控制和部署更容易。
问题是 ProductA 和 B.dll 中的任何依赖项都不能从 WindowsService 发送到 Common dll,因为它需要 WindowsService 中对 ProductA 和 B 的程序集引用(不想要)
因此,单元测试在调用Common.dll中的代码时无法隔离依赖关系。
因此,为了隔离依赖关系,代码有一个重载的构造函数,它只为了测试而暴露依赖关系。
这样好吗?
请看下面的例子:
单元测试会模拟依赖并调用重载的构造函数,但真正的代码调用默认构造函数
public class ClassUnderTest
{
private ISomeDependency a;
private IOtherDependency b;
// constructor called by code
public ClassUnderTest()
{
this.a = new SomeDependency();
this.b = new OtherDependency();
}
public ClassUnderTest(ISomeDependency a, IOtherDependency b)
{
this.a = a;
this.b = b;
}
}
【问题讨论】:
标签: c# unit-testing dependency-injection