public class ExcelHelper : IExcelHelper
{
private ICustomLoadRepository _customLoadRepository;
public ExcelHelper(IUnityContainer unityContainer)
{
_customLoadRepository= unityContainer.Resolve<ICustomLoadRepository>();
}
}我们已经开始使用RhinoMocks对我们的代码进行单元测试。
不确定如何模拟代码行
_customLoadRepository = unityContainer.Resolve<ICustomLoadRepository>();我们不希望通过从构造函数参数传递来解决这个问题,因为类中此类参数的数量有时会超过7-8个。
发布于 2018-02-26 18:30:03
这似乎是一个XY problem。
也就是说,将容器作为依赖注入到任何类中通常被认为是一种不好的做法,因为它违背了使用依赖注入的目的。这种设计与服务定位器模式有更多的共同之处。在这种情况下,它被认为是反模式。
您应该改为练习Explicit Dependencies Principle
方法和类应该显式地要求(通常通过方法参数或构造函数参数)它们需要的任何协作对象才能正常工作。
..。
具有显式依赖关系的类更诚实。它们非常清楚地陈述了执行其特定功能所需的内容。
public class ExcelHelper : IExcelHelper {
private readonly ICustomLoadRepository customLoadRepository;
public ExcelHelper(ICustomLoadRepository customLoadRepository) {
this.customLoadRepository = customLoadRepository;
}
//...
}这可以通过使用Rhino Mocks或任何其他模拟框架注入抽象依赖的模拟来轻松测试。
public void Some_unit_test() {
//Arrange
var stubCustomLoadRepository = MockRepository.GenerateStub<ICustomLoadRepository>();
stubCustomLoadRepository.Stub(_ => _.SomeCustomLoadMethod()).Return("Some value");
var classUnderTest = new ExcelHelper(stubCustomLoadRepository);
//Act
//...exercise class under test
//Assert
//...
}至于你关于有很多构造函数参数的说法,
我们不希望通过从构造函数参数传递来解决这个问题,因为在每个类上,此类参数的数量有时会超过7-8个
我认为这是一种代码气味。这通常表明您的类正在尝试做太多的事情。违反了Single Responsibility Principle (SRP)。
因此,从所有迹象来看,你似乎有一个设计问题。检查您的类,并尝试使用聚合依赖项重构它们。考虑遵循更可靠的设计原则。
https://stackoverflow.com/questions/48981201
复制相似问题