TDD和工厂模式

时间:2016-06-14 11:27:47

标签: java unit-testing tdd

我是tdd的新手。我尝试实现一个从文件中读取配置并执行某些操作的应用程序。

我有一个conf元素接口:

interface ConfElement{
    doSamething()
}

然后我有一个实现ConfElement的两个ConcreteConfElement:

ConcreteConfElementA:

class ConcreteConfElementA implements ConfElement{
     private propA;

     doSamething()
}

ConcreteConfElementB:

class ConcreteConfElementB implements ConfElement{

     private propB;

     doSamething()
}

然后我有一个工厂创建ConcreteConfElementAConcreteConfElementB读取Configuration对象传递给工厂;

ConfElementFactory(){
  public ConfElementFactory(Configuration conf)

  ConfElement createConf(){
     if(conf.hasElA){
         return new ConcreteConfElementA();
     }
     else{
         return new ConcreteConfElementB();
     }
  }
}

我该如何测试工厂方法?它是为tdd设计的吗?

2 个答案:

答案 0 :(得分:0)

测试工厂的条件逻辑应该相对容易。 两项测试可能是:

  1. Configuration对象实例化为hasEla为真。使用测试Configuration对象实例化Element工厂,并断言已返回ConcreteConfElementA的实例。

  2. 重复第一步,但将hasEla设为false,并声明已返回ElementB

  3. 我相信这个特定的工厂是可测试的,因为它允许调用者注入Configuration

答案 1 :(得分:0)

使用TDD,您需要在生产代码之前首先编写测试。 TDD鼓励设计模式超时而不是直接出现。

  • 为用例1编写测试
  • 实施足够的代码以通过此测试(无接口!)
  • 测试通行证
  • 为用例2编写测试
  • 实施足够的代码以通过此测试
  • 测试通行证
  • 重构以删除重复项(提示:出现工厂模式!)

这样,代码经过100%测试,无需担心模式是否可测试。重构是TDD的关键要素。

相关问题