依赖注入(inject)对于测试具有依赖性的模块非常有用。这与那些无关。
说有一些具体的实现,
public class DoesSomething : IDoesSomething
{
public int DoesImportant(int x, int y)
{
// perform some operation
}
}
实现这个,
public interface IDoesSomething
{
int DoesImportant(int x, int y);
}
在单元测试中,您显然可以新建
测试,
[TestMethod]
public void DoesSomething_CanDoDoesImportant()
{
int expected = 42;
IDoesSomething foo = new DoesSomething();
int actual = foo.DoesImportant(21, 2);
Assert.AreEqual(expected, actual);
}
或使用 DI(这里使用 Autofac,但对于问题的原则应该无关紧要),
[TestMethod]
public void DoesSomething_CanDoDoesImportant()
{
var builder = new ContainerBuilder();
builder.RegisterType<DoesSomething>().As<IDoesSomething>();
var container = builder.Build();
int expected = 42;
IDoesSomething foo = container.Resolve<IDoesSomething>();
int actual = foo.DoesImportant(21, 2);
Assert.AreEqual(expected, actual);
}
鉴于这样一个没有依赖关系的独立模块,是否有令人信服的理由将 IDoesSomething
注入(inject)到测试中?或者,是否有令人信服的理由不注入(inject)IDoesSomething
?
最佳答案
此测试不需要使用 DI 容器。
这就是您可以使用 DI 容器来解析具体类的原因:所有其他测试都使用类似的模式通过容器构造类型,而这个恰好不需要依赖项。
统一示例:
[TestMethod]
public void DoesSomething_behaves_correctly()
{
var expected = 42;
var container = new UnityContainer();
var foo = container.Resolve<DoesSomething>();
int actual = foo.DoesImportant(21, 21);
Assert.AreEqual(expected, actual);
}
这种方法的附带好处是,当 DoesSomething
开始具有依赖项时,您的测试只需进行最少的更改。
关于c# - 在单元测试中将 DI 与没有依赖关系的模块/类一起使用是否有令人信服的理由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31576489/