服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 高级技术 > 设计模式 > 查看文档

追逐代码质量: 决心采用 fit

  junit 假定测试的所有方面都是开发人员的地盘,而集成测试框架(fit)在编写需求的业务客户和实现需求的开发人员之间做了协作方面的试验。这是否意味着 fit 和 junit 是竞争关系呢?绝对不是!代码质量完美主义者 andrew glover 介绍了如何把 fit 和 junit 两者最好的地方结合在一起,实现更好的团队工作和有效的端到端测试。

  在软件开发的生命周期中,每个人都对质量负有责任。理想情况下,开发人员在开发周期中,用像 junit 和 testng 这样的测试工具保证早期质量,而质量保证团队用功能性系统测试在周期末端跟进,使用像 selenium 这样的工具。但是即使拥有优秀的质量保证,有些应用程序在交付的时候仍然被认为是质量低下的。为什么呢?因为它们并没有做它们应当做的事。

  在客户、(编写应用程序需求的)业务部门和(实现需求的)开发团队之间的沟通错误,通常是摩擦的原因,有时还是开发项目彻底失败的常见原因。幸运的是,存在一些方法可以帮助需求作者和实现者之间尽早 沟通。

  fit 化的解决方案

  集成测试框架 (fit)是一个测试平台,可以帮助需求编写人员和把需求变成可执行代码的人员之间的沟通。使用 fit,需求被做成表格模型,充当开发人员编写的测试的数据模型。表格本身充当输入和测试的预期输出。

  图 1 显示了用 fit 创建的结构化模型。第一行是测试名称,下一行的三列是与输入(value1value2)和预期结果(trend())有关的标题。


  图 1. 用 fit 创建的结构化模型

  好消息是,对于编程没有经验的人也能编写这个表格。fit 的设计目的就是让消费者或业务团队在开发周期中,尽早与实现他们想法的开发人员协作。创建应用程序需求的简单表格式模型,可以让每个人清楚地看出代码和需求是否是一致的。

  清单 1 是与图 1 的数据模型对应的 fit 代码。不要太多地担心细节 ―― 只要注意代码有多么简单,而且代码中没有包含验证逻辑(例如,断言等)。可能还会注意到一些与表 1 中的内容匹配的变量和方法名称;关于这方面的内容后面介绍。


  清单 1. 根据 fit 模型编写的代码


package test.com.acme.fit.impl;

import com.acme.sedlp.trend.trender;
import fit.columnfixture;

public class trendindicator extends columnfixture {

  public double value1;
  public double value2;

  public string trend(){		
    return trender.determinetrend(value1, value2).getname();
  }
}

  清单 1 中的代码由研究上面表格并插入适当代码的开发人员编写。最后,把所有东西合在一起,fit 框架读取表 1 的数据,调用对应的代码,并确定结果。



  fit 和 junit

  fit 的优美之处在于,它让组织的消费者或业务端能够尽早参与测试过程(例如,在开发期间)。junit 的力量在于编码过程中的单元测试,而 fit 是更高层次的测试工具,用来判断规划的需求实现的正确性。

  例如,虽然 junit 擅长验证两个 money 对象的合计与它们的两个值的合计相同,但 fit 可以验证总的订单价格是其中商品的价格减去任何相关折扣之后的合计。区别虽然细微,但的确重大!在 junit 示例中,要处理具体的对象(或者需求的实现),但是使用 fit 时要处理的是高级的业务过程。 

  这很有意义,因为编写需求的人通常不太考虑 money 对象 ―― 实际上,他们可能根本不知道这类东西的存在!但是,他们确实要考虑,当商品被添加到订单时,总的订单价格应当是商品的价格减去所有折扣。

  fit 和 junit 之间绝不是竞争关系,它们是保证代码质量的好搭档,正如在后面的 案例研究 中将要看到的。



  测试用的 fit 表格

  表格是 fit 的核心。有几种不同类型的表格(用于不同的业务场景),fit 用户可以用不同的格式编写表格。用 html 编写表格甚至用 microsoft excel 编写都是可以的,如图 2 所示:


  图 2. 用 microsoft excel 编写的表格

  也有可能用 microsoft word 这样的工具编写表格,然后用 html 格式保存,如图 3 所示:


  图 3. 用 microsoft word 编写的表格

  开发人员编写的用来执行表格数据的代码叫作装备(fixture)。要创建一个装备类型,必须扩展对应的 fit 装备,它映射到对应的表。如前所述,不同类型的表映射到不同的业务场景。


  用装备进行装配

  最简单的表和装备组合,也是 fit 中最常用的,是一个简单的列表格,其中的列映射到预期过程的输入和输出。对应的装备类型是 columnfixture

  如果再次查看 清单 1,将注意到 trendindicator 类扩展了 columnfixture,而且也与图 3 对应。请注意在图 3 中,第一行的名称匹配完全限定名称(test.com.acme.fit.impl.trendindicator)。下一行有三列。头两个单元格的值匹配 trendindicator 类的 public 实例成员(value1value2),最后一个单元格的值只匹配 trendindicator 中的方法(trend)。

  现在来看清单 1 中的 trend 方法。它返回一个 string 值。可以猜测得到,对于表中每个剩下的行,fit 都会替换值并比较结果。在这个示例中,有三个 “数据” 行,所以 fit 运行 trendindicator 装备三次。第一次,value1 被设置成 84.0,value2 设置成 71.2。然后 fit 调用 trend 方法,并把从方法得到的值与表中的值比较,应当是 “decreasing”。

  通过这种方式,fit 用装备代码测试 trender 类,每次 fit 执行 trend 方法时,都执行类的 determinetrend 方法。当代码测试完成时,fit 生成如图 4 所示的报告:


  图 4. fit 报告 trend 测试的结果

  trend 列单元格的绿色表明测试通过(例如,fit 设置 value1 为 84.0,value2 为 71.2,调用 trend 得到返回值 “decreasing”)。


  查看 fit 运行

  可以通过命令行,用 ant 任务并通过 maven 调用 fit,从而简单地把 fit 测试插入构建过程。因为自动进行 fit 测试,就像 junit 测试一样,所以也可以定期运行它们,例如在持续集成系统中。

  最简单的命令行运行器,如清单 2 所示,是 fit 的 folderrunner,它接受两个参数 ―― 一个是 fit 表格的位置,一个是结果写入的位置。不要忘记配置类路径!


  清单 2. fit 的命令行


%>java fit.runner.folderrunner ./test/fit ./target/

  fit 通过插件,还可以很好地与 maven 一起工作,如清单 3 所示。只要下载插件,运行 fit:fit 命令,就 ok 了!


  清单 3. maven 得到 fit


c:\dev\proj\edoa>maven fit:fit
 __  __
|  \/  |__ _apache__ ___
| |\/| / _` \ v / -_) ' \  ~ intelligent projects ~
|_|  |_\__,_|\_/\___|_||_|  v. 1.0.2

build:start:

java:prepare-filesystem:

java:compile:
    [echo] compiling to c:\dev\proj\edoa/target/classes

java:jar-resources:

test:prepare-filesystem:

test:test-resources:

test:compile:

fit:fit:
    [java] 2 right, 0 wrong, 0 ignored, 0 exceptions
build successful
total time: 4 seconds
finished at: thu feb 02 17:19:30 est 2006


  试用 fit:案例研究

  现在已经了解了 fit 的基础知识,我们来做一个练习。如果还没有 下载 fit,现在是下载它的时候了!如前所述,这个案例研究显示出可以容易地把 fit 和 junit 测试组合在一起,形成多层质量保证。

  假设现在要为一个酿酒厂构建一个订单处理系统。酿酒厂销售各种类型的酒类,但是它们可以组织成两大类:季节性的和全年性的。因为酿酒厂以批发方式运作,所以酒类销售都是按桶销售的。对于零售商来说,购买多桶酒的好处就是折扣,而具体的折扣根据购买的桶数和酒是季节性还是全年性的而不同。

  麻烦的地方在于管理这些需求。例如,如果零售店购买了 50 桶季节性酒,就没有折扣;但是如果这 50 桶不是 季节性的,那么就有 12% 的折扣。如果零售店购买100 桶季节性酒,那就有折扣,但是只有 5%。100 桶更陈的非季节性酒的折扣达到 17%。购买量达到 200 时,也有类似的规矩。

  对于开发人员,像这样的需求集可能让人摸不着头脑。但是请看,我们的啤酒-酿造行业分析师用 fit 表可以很容易地描述出这个需求,如图 5 所示:


  图 5. 我的业务需求非常清晰!

  表格语义

  这个表格从业务的角度来说很有意义,它确实很好地规划出需求。但是作为开发人员,还需要对表格的语言了解更多一些,以便从表格得到值。首先,也是最重要的,表格中的初始行说明表格的名称,它恰好与一个匹配的类对应(org.acme.store.discount.discountstructurefit)。命名要求表格作者和开发人员之间的一些协调。至少,需要指定完全限定的表格名称(也就是说,必须包含包名,因为 fit 要动态地装入对应的类)。

  请注意表格的名称以 fit 结束。第一个倾向可能是用 test 结束它,但要是这么做,那么在自动环境中运行 fit 测试和 junit 测试时,会与 junit 产生些冲突,junit 的类通常通过命名模式查找,所以最好避免用 test 开始或结束 fit 表格名称。

  下一行包含五列。每个单元格中的字符串都特意用斜体格式,这是 fit 的要求。前面学过,单元格名称与装备的实例成员和方法匹配。为了更简洁,fit 假设任何值以括号结束的单元格是方法,任何值不以括号结束的单元格是实例成员。

  特殊智能

  fit 在处理单元格的值,进行与对应装备类的匹配时,采用智能解析。如 图 5 所示,第二行单元格中的值是用普通的英文编写的,例如 “number of cases”。fit 试图把这样的字符串按照首字母大写方式连接起来;例如,“number of cases” 变成 “numberofcases”,然后 fit 试图找到对应的装备类。这个原则也适用于方法 ―― 如图 5 所示,“discount price()” 变成了 “discountprice()”。

  fit 还会智能地猜测单元格中值的具体类型。例如,在 图 5 余下的八行中,每一列都有对应的类型,或者可以由 fit 准确地猜出,或者要求一些定制编程。在这个示例中,图 5 有三种不同类型。与 “number of cases” 关联的列匹配到 int,而与 “is seasonal” 列关联的值则匹配成 boolean

  剩下的三列,“list price per case”、“discount price()” 和 “discount amount()” 显然代表当前值。这几列要求定制类型,我将把它叫作 money。有了它之后,应用程序就要求一个代表钱的对象,所以在我的 fit 装备中遵守少量语义就可以利用上这个对象!

  fit 语义总结

  表 1 总结了命名单元格和对应的装备实例变量之间的关系:


  表 1. 单元格到装备的关系:实例变量

  单元格值 对应的装备实例变量 类型
  list price per case listpricepercase money
  number of cases numberofcases int
  is seasonal isseasonal boolean

  表 2 总结了 fit 命名单元格和对应的装备方法之间的关系:


  表 2. 单元格到装备的关系:方法

  表格单元格的值 对应的装备方法 返回类型
  discount price() discountprice money
  discount amount() discountamount money



  该构建了!

  要为酿酒厂构建的订单处理系统有三个主要对象:一个 pricingengine 处理包含折扣的业务规则,一个 wholesaleorder 代表订单,一个 money 类型代表钱。

  money 类

  第一个要编写的类是 money 类,它有进行加、乘和减的方法。可以用 junit 测试新创建的类,如清单 14 所示:

  
  清单 4. junit 的 moneytest 类


package org.acme.store;

import junit.framework.testcase;

public class moneytest extends testcase {

  public void testtostring() throws exception{
    money money = new money(10.00);
    money total = money.mpy(10);
    assertequals("$100.00", total.tostring());
  }

  public void testequals() throws exception{
    money money = money.parse("$10.00");
    money control = new money(10.00);
    assertequals(control, money); 
  }

  public void testmultiply() throws exception{
    money money = new money(10.00);
    money total = money.mpy(10);
  
    money discountamount = total.mpy(0.05);    
    assertequals("$5.00", discountamount.tostring());
  }

  public void testsubtract() throws exception{
    money money = new money(10.00);
    money total = money.mpy(10);

    money discountamount = total.mpy(0.05);
    money discountedprice = total.sub(discountamount);
    assertequals("$95.00", discountedprice.tostring());
  }
}

  wholesaleorder 类

  然后,定义 wholesaleorder 类型。这个新对象是应用程序的核心:如果 wholesaleorder 类型配置了桶数、每桶价格和产品类型(季节性或全年性),就可以把它交给 pricingengine,由后者确定对应的折扣并相应地在 wholesaleorder 实例中配置它。

  wholesaleorder 类的定义如清单 5 所示:


  清单 5. wholesaleorder 类


package org.acme.store.discount.engine;

import org.acme.store.money;

public class wholesaleorder {

  private int numberofcases;
  private producttype producttype;	
  private money pricepercase;	
  private double discount;

  public double getdiscount() {
    return discount;
  }

  public void setdiscount(double discount) {
    this.discount = discount;
  }

  public money getcalculatedprice() {
    money totalprice = this.pricepercase.mpy(this.numberofcases);
    money tmpprice = totalprice.mpy(this.discount);
     return totalprice.sub(tmpprice);
  }

  public money getdiscounteddifference() {        
    money totalprice = this.pricepercase.mpy(this.numberofcases);
    return totalprice.sub(this.getcalculatedprice());
  }

  public int getnumberofcases() {
    return numberofcases;
  }

  public void setnumberofcases(int numberofcases) {
    this.numberofcases = numberofcases;
  }

  public void setproducttype(producttype producttype) {
    this.producttype = producttype;
  }

  public string getproducttype() {
    return producttype.getname();
  }

  public void setpricepercase(money pricepercase) {
    this.pricepercase = pricepercase;
  }

  public money getpricepercase() {
    return pricepercase;
  }	
}

  从清单 5 中可以看到,一旦在 wholesaleorder 实例中设置了折扣,就可以通过分别调用 getcalculatedpricegetdiscounteddifference 方法得到折扣价格和节省的钱。

  更好地测试这些方法(用 junit)!

  定义了 moneywholesaleorder 类之后,还要编写 junit 测试来验证 getcalculatedpricegetdiscounteddifference 方法的功能。测试如清单 6 所示:


  清单 6. junit 的 wholesaleordertest 类


package org.acme.store.discount.engine.junit;

import junit.framework.testcase;
import org.acme.store.money;
import org.acme.store.discount.engine.wholesaleorder;

public class wholesaleordertest extends testcase {

  /*
   * test method for 'wholesaleorder.getcalculatedprice()'
   */
  public void testgetcalculatedprice() {
    wholesaleorder order = new wholesaleorder();
    order.setdiscount(0.05);
    order.setnumberofcases(10);
    order.setpricepercase(new money(10.00));

    assertequals("$95.00", order.getcalculatedprice().tostring());
  }

  /*
   * test method for 'wholesaleorder.getdiscounteddifference()'
   */
  public void testgetdiscounteddifference() {
    wholesaleorder order = new wholesaleorder();
    order.setdiscount(0.05);
    order.setnumberofcases(10);
    order.setpricepercase(new money(10.00));

    assertequals("$5.00", order.getdiscounteddifference().tostring());
  }
}

  pricingengine 类

  pricingengine 类利用业务规则引擎,在这个示例中,是 drools。pricingengine 极为简单,只有一个 public 方法:applydiscount。只要传递进一个 wholesaleorder 实例,引擎就会要求 drools 应用折扣,如清单 7 所示:


  清单 7. pricingengine 类


package org.acme.store.discount.engine;

import org.drools.rulebase;
import org.drools.workingmemory;
import org.drools.io.rulebaseloader;

public class pricingengine {

  private static final string rules="businessrules.drl";
  private static rulebase businessrules;

  private static void loadrules() throws exception{
    if (businessrules==null){			
      businessrules = rulebaseloader.
         loadfromurl(pricingengine.class.getresource(rules));
    }
  }	

  public static void applydiscount(wholesaleorder order) throws exception{
    loadrules();             
    workingmemory workingmemory = businessrules.newworkingmemory( );
    workingmemory.assertobject(order);       
    workingmemory.fireallrules();		
  }
}

 

  drools 的规则

  必须在特定于 drools 的 xml 文件中定义计算折扣的业务规则。例如,清单 8 中的代码段就是一个规则:如果桶数大于 9,小于 50,不是季节性产品,则订单有 5% 的折扣。

  清单 8. businessrules.drl 文件的示例规则



<rule-set name="businessrulessample"
          xmlns="http://drools.org/rules"
          xmlns:java="http://drools.org/semantics/java"
          xmlns:xs="http://www.w3.org/2001/xmlschema-instance"
          xs:schemalocation="http://drools.org/rules rules.xsd
                             http://drools.org/semantics/java java.xsd">
<rule name="1st tier discount">
  <parameter identifier="order">
    <class>wholesaleorder</class>
  </parameter>

  <java:condition>order.getnumberofcases() > 9 </java:condition>
  <java:condition>order.getnumberofcases() < 50 </java:condition>
  <java:condition>order.getproducttype() == "year-round"</java:condition>

  <java:consequence>      
    order.setdiscount(0.05);
  </java:consequence>
</rule>
</rule-set>




  标记团队测试

  有了 pricingengine 并定义了应用程序规则之后,可能渴望验证所有东西都工作正确。现在问题就变成,用 junit 还是 fit?为什么不两者都用呢?通过 junit 测试所有组合是可能的,但是要进行许多编码。最好是用 junit 测试少数几个值,迅速地验证代码在工作,然后依靠 fit 的力量运行想要的组合。请看看当我这么尝试时发生了什么,从清单 9 开始:


  清单 9. junit 迅速地验证了代码在工作


package org.acme.store.discount.engine.junit;

import junit.framework.testcase;
import org.acme.store.money;
import org.acme.store.discount.engine.pricingengine;
import org.acme.store.discount.engine.producttype;
import org.acme.store.discount.engine.wholesaleorder;

public class discountenginetest extends testcase {

  public void testcalculatediscount() throws exception{
    wholesaleorder order = new wholesaleorder();
    order.setnumberofcases(20);
    order.setpricepercase(new money(10.00));
    order.setproducttype(producttype.year_round);

    pricingengine.applydiscount(order);

    assertequals(0.05, order.getdiscount(), 0.0);
  }

  public void testcalculatediscountnone() throws exception{
    wholesaleorder order = new wholesaleorder();
    order.setnumberofcases(20);
    order.setpricepercase(new money(10.00));
    order.setproducttype(producttype.seasonal);
    
    pricingengine.applydiscount(order);

    assertequals(0.0, order.getdiscount(), 0.0);
  }
}

  还没用 fit?那就用 fit!

  在 图 5 的 fit 表格中有八行数据值。可能已经在 清单 7 中编写了前两行的 junit 代码,但是真的想编写整个测试吗?编写全部八行的测试或者在客户添加新规则时再添加新的测试,需要巨大的耐心。好消息就是,现在有了更容易的方法。不过,不是忽略测试 ―― 而是用 fit! 

  fit 对于测试业务规则或涉及组合值的内容来说非常漂亮。更好的是,其他人可以完成在表格中定义这些组合的工作。但是,在为表格创建 fit 装备之前,需要给 money 类添加一个特殊方法。因为需要在 fit 表格中代表当前货币值(例如,像 $100.00 这样的值),需要一种方法让 fit 能够认识 money 的实例。做这件事需要两步:首先,必须把 static parse 方法添加到定制数据类型,如清单 10 所示:


清单 10. 添加 parse 方法到 money 类


 public static money parse(string value){
   return new money(double.parsedouble(stringutils.remove(value, '$')));
 }

  money 类的 parse 方法接受一个 string 值(例如,fit 从表格中取出的值)并返回配置正确的 money 实例。在这个示例中,$ 字符被删除,剩下的 string 被转变成 double,这与 money 中现有的构造函数匹配。

  不要忘记向 moneytest 类添加一些测试来来验证新添加的 parse 方法按预期要求工作。两个新测试如清单 11 所示:

 
  清单 11. 测试 money 类的 parse 方法


 public void testparse() throws exception{
   money money = money.parse("$10.00");
   assertequals("$10.00", money.tostring());
 }

 public void testequals() throws exception{
   money money = money.parse("$10.00");
   money control = new money(10.00);
   assertequals(control, money);
}

  编写 fit 装备

  现在可以编写第一个 fit 装备了。实例成员和方法已经在表 1 和表 2 中列出,所以只需要把事情串在一起,添加一两个方法来处理定制类型:money。为了在装备中处理特定类型,还需要添加另一个 parse 方法。这个方法的签名与前一个略有不同:这个方法是个对 fixture 类进行覆盖的实例方法,这个类是 columnfixture 的双亲。

  请注意在清单 12 中,discountstructurefitparse 方法如何比较 class 类型。如果存在匹配,就调用 money 的定制 parse 方法;否则,就调用父类(fixture)的 parse 版本。

  清单 12 中剩下的代码是很简单的。对于图 5 所示的 fit 表格中的每个数据行,都设置值并调用方法,然后 fit 验证结果!例如,在 fit 测试的第一次运行中,discountstructurefitlistpricepercase 被设为 $10.00,numberofcases 设为 10,isseasonal 为 true。然后执行 discountstructurefitdiscountprice,返回的值与 $100.00 比较,然后执行 discountamount,返回的值与 $0.00 比较。


  清单 12. 用 fit 进行的折扣测试


package org.acme.store.discount;

import org.acme.store.money;
import org.acme.store.discount.engine.pricingengine;
import org.acme.store.discount.engine.producttype;
import org.acme.store.discount.engine.wholesaleorder;
import fit.columnfixture;

public class discountstructurefit extends columnfixture {

  public money listpricepercase;
  public int numberofcases;
  public boolean isseasonal;

  public money discountprice() throws exception {
    wholesaleorder order = this.doordercalculation();
    return order.getcalculatedprice();
  }

  public money discountamount() throws exception {
    wholesaleorder order = this.doordercalculation();
    return order.getdiscounteddifference();
  }

 /**
  * required by fit for specific types
  */
  public object parse(string value, class type) throws exception {
    if (type == money.class) {
      return money.parse(value);
    } else {
      return super.parse(value, type);
    }
  }

  private wholesaleorder doordercalculation() throws exception {
    wholesaleorder order = new wholesaleorder();
    order.setnumberofcases(numberofcases);
    order.setpricepercase(listpricepercase);

    if (isseasonal) {
      order.setproducttype(producttype.seasonal);
    } else {
      order.setproducttype(producttype.year_round);
    }

    pricingengine.applydiscount(order);
    return order;
  }
}

  现在,比较 清单 9 的 junit 测试用例和清单 12。是不是清单 12 更有效率?当然可以 用 junit 编写所有必需的测试,但是 fit 可以让工作容易得多!如果感觉到满意(应当是满意的!),可以运行构建,调用 fit 运行器生成如图 6 所示的结果:


  图 6. 这些结果真的很 fit !



  结束语

  fit 可以帮助企业避免客户和开发人员之间的沟通不畅、误解和误读。把编写需求的人尽早 带入测试过程,是在问题成为开发恶梦的根源之前发现并修补它们的明显途径。而且,fit 与现有的技术(比如 junit)完全兼容。实际上,正如本文所示,junit 和 fit 互相补充。请把今年变成您追逐代码质量 的重要纪年 ―― 由于决心采用 fit!

扫描关注微信公众号