TDD的嵌套类?

时间:2016-08-26 20:53:19

标签: java unit-testing tdd

当我在TDD之后编写代码时,我经常发现自己正在创建小类以使测试更容易。然而,通常这些小类仅由一个类使用,因此你可以认为凝聚力受到影响,因为现在在一个类中具有强大内聚力的逻辑通过多个类传播。

所以问题是有一种使用嵌套包私有类来拆分逻辑的做法。单元测试仍然可以注入这些类的模拟实现,而内聚力不会受到太多影响,因为这些嵌套类仍然存在于一个类下。

所以而不是:

@Component
public class A {

  @Autowire
  private B b; 

  public void doPublicStuff(){
     for (...){
       b.doImplementationStuff(..);      
     }
  }  
}

@Component
class B {
  doImplementationStuff(){}
}

这就像是

@Componenet 
public class A {

  // Allow injection for unit tests
  A(B b, SomeOtherClass someOtherClass){
   this.b = b;
   this.someOtherClass = someOtherClass;
  }

  public A(){ 
     // gets instantiated in default constructor to expected implementation
     b = new B();
  }

  private B b; 

  @Autowire
  private SomeOtherClass someOtherClass;

  public void doPublicStuff(){
     for (...){
       b.doImplementationStuff(..);      
     }
  }  

  class B {
    doImplementationStuff(){}
  }
}

2 个答案:

答案 0 :(得分:0)

你的措辞让我困惑:其他人?

首先我读了

  

通常这些小班只用于一个班级

我进一步向下看:

  现在,在一个阶级中具有强大凝聚力的逻辑被传播开来   多个班级。

这是什么?一个或多个班级?

我猜你是在过度思考它。我不能从你的例子中说出来。

单元测试应该检查一个类。注入依赖项的模拟。测试方法,包括快乐路径和特殊路径。什么这么难?

在您的情况下,我会将BSomeOtherClass的模拟注入A。我期待每个单元的单元测试,与A的测试分开。无需在A的测试中重新练习它们。

答案 1 :(得分:0)

我喜欢你的例子中使用的嵌套私有类方法。以这种方式使用它并不会失去可测试性是有道理的。虽然,我不知道这是一种标准做法。