【发布时间】:2010-09-30 01:29:01
【问题描述】:
在我的分析器报告中,我越来越多地看到使用依赖注入进行基于模拟的测试的结果。许多依赖项是静态的,但因为我们想单独测试方法,所以将它们更改为实例成员,如下例所示:
class ShortLivedThing {
IDependency1 dep1;
IDependency1 dep2;
IDependency1 dep3;
...
int TheRealData;
// Constructor used in production
public ShortLivedThing() {
dep1 = new Dep1(); dep2 = new Dep2(); dep3 = new Dep3();
}
// DI for testing
public ShortLivedThing(IDependency1 d1, IDependency2 d2, IDependency3 d3) {
dep1 = d1(); dep2 = d2(); dep3 = d3();
}
}
反过来,大多数时候依赖项还有其他依赖项等等。这会导致实例化(主要是“静态”)对象树每次在测试之外进行方法调用。每个对象都非常小(只有几个指针),但树效应将其转化为不断增加的性能损失。
我们能做些什么呢?
【问题讨论】:
-
你是在分析你的生产代码还是你的测试?
-
我正在分析生产代码。测试运行速度很快,因为它们不构建依赖项的依赖项。