【问题标题】:TDD and Factory PatternTDD 和工厂模式
【发布时间】:2016-06-14 11:27:47
【问题描述】:

我是 TDD 新手。我尝试实现一个从文件中读取配置并做一些事情的应用程序。

我有一个conf元素界面:

interface ConfElement{
    doSomething()
}

然后我有两个 ConcreteConfElement 实现ConfElement:

ConcreteConfElementA:

class ConcreteConfElementA implements ConfElement{
     private propA;

     doSomething()
}

ConcreteConfElementB:

class ConcreteConfElementB implements ConfElement{

     private propB;

     doSomething()
}

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

ConfElementFactory(){
  public ConfElementFactory(Configuration conf)

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

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

【问题讨论】:

    标签: java unit-testing tdd


    【解决方案1】:

    测试你工厂的条件逻辑应该比较容易。 两个测试可能是:

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

    2. 重复第一步,但将hasEla设置为false,并断言ElementB已返回。


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

    【讨论】:

      【解决方案2】:

      使用 TDD,您需要先编写测试,然后再编写生产代码。 TDD 鼓励设计模式随着时间的推移而出现,而不是立即出现。

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

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

      【讨论】:

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