【问题标题】:Mock IOC Unity Object Creation call模拟 IOC Unity 对象创建调用
【发布时间】:2018-02-26 03:52:23
【问题描述】:
public class ExcelHelper : IExcelHelper
{
    private ICustomLoadRepository _customLoadRepository;
    public ExcelHelper(IUnityContainer unityContainer)
    {
         _customLoadRepository= unityContainer.Resolve<ICustomLoadRepository>(); 
    }
}

我们已经开始使用 RhinoMocks 对我们的代码进行单元测试。

不知道如何模拟代码行

_customLoadRepository = unityContainer.Resolve<ICustomLoadRepository>();

我们不希望通过从构造函数参数传递来解决它,因为此类参数的数量有时会在类上达到 7-8 个以上。

【问题讨论】:

    标签: c# unit-testing dependency-injection rhino-mocks


    【解决方案1】:

    这似乎是XY problem

    也就是说,将容器作为依赖项注入任何类通常被认为是一种不好的做法,因为它违背了使用依赖项注入的目的。这样的设计与 Service Locator 模式有更多的共同点。在这种情况下,这被认为是一种反模式。

    你应该练习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)

    因此,从所有迹象来看,您似乎遇到了设计问题。查看您的类并尝试使用聚合依赖项重构它们。考虑遵循更可靠的设计原则。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-26
      • 2017-01-09
      相关资源
      最近更新 更多