c# - 如何在没有 DI 的情况下在紧密耦合的业务/数据层上启用单元测试?

标签 c# unit-testing dependency-injection

我正在处理一个旧的 3 层设计项目,添加的任何新功能都需要进行单元测试。

问题是业务层/数据层紧密耦合,如下例所示。 BL 只是新闻了一个数据层对象...所以几乎不可能以这种方式进行模拟。我们没有实现任何依赖注入(inject),因此构造函数注入(inject)是不可能的。那么修改结构以便在不使用 DI 的情况下模拟数据层的最佳方法是什么?

public class BLLayer()
{

   public GetBLObject(string params)
   {
     using(DLayer dl = new DLayer())
     {  
        DataSet ds = dl.GetData(params);

        BL logic here....

     }
   }
}

最佳答案

您没有排除构造函数注入(inject)本身,您只是没有设置 IOC 容器。没关系,你不需要一个。您可以执行穷人的依赖注入(inject)并仍然保留构造函数注入(inject)。

用接口(interface)包装 DataLayer,然后创建一个工厂,根据命令生成 IDataLayer 对象。将此作为字段添加到您要注入(inject)的对象中,将所有 new 替换为对工厂的调用。现在你可以注入(inject)你的假货进行测试,就像这样:

interface IDataLayer { ... }
interface IDataLayerFactory 
{
   IDataLayer Create();
}    

public class BLLayer()
{
  private IDataLayerFactory _factory;

   // present a default constructor for your average consumer
  ctor() : this(new RealFactoryImpl()) {} 

  // but also expose an injectable constructor for tests
  ctor(IDataLayerFactory factory)
  { 
    _factory = factory;
  }  

  public GetBLObject(string params)
  {
    using(DLayer dl = _factory.Create())  // replace the "new"
    {  
      //BL logic here....    
    }
  }
}

不要忘记为要在实际代码中使用的实际工厂设置默认值。

关于c# - 如何在没有 DI 的情况下在紧密耦合的业务/数据层上启用单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10857932/

相关文章:

c# - MVVM View 模型事件(命令?)

c# - 在 C# 中的单元测试中设置命令行参数

c# - 将 C# 字符串分析为不同的变量

unit-testing - 单元测试在构建服务器上执行缓慢

java - 使用 Maven 进行 Google App Engine 数据存储单元测试

java - 无法掌握 Guice 方法拦截器的窍门(bindInterceptor 期间出现空指针异常)

c# - 从另一个ViewModel访问属性

Angular 单元测试 : how to use marble testing (rxjs/testing) to test this state management service

javascript - 如何在 redux-sagas 中注入(inject)依赖项(或上下文)

dependency-injection - 如何在 UML 中建模依赖注入(inject)?