`引言
一个例子
我们先看一个例子,以了解对”规则”做单元测试的特点。我们有一个性能调优工具 WPA, 它能够将与性能相关的参数的值进行评估并推荐最优值。它的评估和推荐最优值算法都是基于”规则”的。
Java 虚拟机的初始堆大小(JVM initial heap size)是一个影响 JVM 的性能的关键参数。性能调优工具 WPA 有一套规则对“ JVM initial heap size ”的值进行评估(参见清单 1)。评估的结果有 5 个级别。级别“ 1 ”表示设置良好,可提高性能;级别“ 5 ”表示设置很差,会降低性能。
清单 1. JVM initial heap size rating algorithm
Rating3UpperBounds = 1024 Rating3LowerBounds = 48 Rating5UpperBounds = 1536 Rating5LowerBounds = 32 Rating3Multiplier = 4 Rating5Multiplier = 3 absoluteMaximumValue= Math.min(currentMemoryPoolSize, overallMemoryOnPartition) / Rating3Multiplier if (initialHeapSize > absoluteMaximumValue) { return 4; } if ((initialHeapSize < Rating5LowerBounds) || (initialHeapSize > Rating5UpperBounds)) { rating = severe problem (5) } else if ((initialHeapSize < Rating3LowerBounds) || (initialHeapSize > Rating3UpperBounds)) { rating = probable problem (3) } …… } if (initialHeapSize * Rating5Multiplier > currentMemoryPoolSize) { return severe problem (5) } else if(initialHeapSize*Rating3Multiplier > currentMemoryPoolSize) { return max(rating, 3) } else if(initialHeapSize*Rating2Multiplier > currentMemoryPoolSize) else { return max(rating, 1) }
在这一套规则中,有三个输入参数:“initialHeapSize”(“JVM initial heap size”的值),“currentMemoryPoolSize” ( 内存池的值 ) 和“overallMemoryOnPartition”(物理内存的值)。为了得到这些值,我们需要使用 Application Server 和 OS 提供的 API 。在使用这些 API 的时候,我们必须构造出 API 所需的运行环境。
在这一套规则中,包含很多不同的条件(见“ IF-ELSE ”语句)。在测试时(单元测试和功能测试),我们需要至少 24 组测试数据以覆盖所有的阀值(threshold value)和等价类(equivalent class)。参见表 1。
对”规则”做单元测试
从“JVM initial heap size rating algorithm”以及 WPA 中其他基于“规则”的性能调优算法,我们总结出对“规则”做单元测试的特点有:
一、为了覆盖所有的阀值 (threshold value )和等价类 (equivalent class ),我们需要大量测试数据。单元测试的通常做法是,把所有的测试数据写入测试代码中。对比以格式化的形式(XML,Excel 等)来保存测试数据,这样做使得这些数据不容易维护和复用。
二、由于对”规则”的测试涉及到变量,这些变量来自运行时的输入,我们在单元测试之前就需要构建运行时环境,这种工作可能非常复杂。如果一套”规则”中包含更多的条件和输入参数,以上两个问题会更加严重
三、在一个基于”规则”的系统里,”规则”之间有很多共性,我们没有必要对每一个”规则”都写一个测试类。
本文将给出解决以上问题的一种做法。本文的组织结构如下:
编写 Mock 类
为了测试” JVM initial heap size rating algorithm ”,我们需要获得三个输入参数。然而,获取这三个参数并不是那么容易。
为了简化测试环境,我们利用 Mock 对象来设置这些参数。
Mock 对象是单元测试经常用到的一种技术,Mock 对象能模拟实际对象的行为,并且提供了额外的行为控制接口。还有一个常用到的词是 Dummy 对象。 Mock 和 Dummy 的含义经常被混淆。在这里,我们认为 Dummy 对象没有提供额外的行为控制接口。
对于” JVM initial heap size rating algorithm ”,我们需要一个 Mock 类,它的行为与“ InitialHeapSize.java ”相同(“ InitialHeapSize.java ”是 “ JVM initial heap size rating algorithm ”的 Java 代码)。我们把这个 Mock 类命名为“ MockInitialHeapSize.java ”。一个 Client 类可以把“ initialHeapSize ” , “ currentMemoryPoolSize ” , 和“ overallMemoryOnPartition ” 直接设置到“ MockInitialHeapSize ”对象中。参见清单 2
清单 2. MockInitialHeapSize.java
public class MockInitialHeapSize extends InitialHeapSize { // 设置 InitialHeapSize public void setInitialValue(String initialValue){ this.initialValue = initialValue; } // 设置 MemoryPoolSize public void mockSetMemoryPoolSize(String size) { try{ this.currentSettingOfMemoryPoolSize=Float.parseFloat(size); }catch(NumberFormatException ne){ Advisor.getLogger().severe("size: " size " are not an float value."); } } // 设置 OverallMemory public void mockSetOverallMemory(String size) { try{ this.overallMemoryOnPartition=Float.parseFloat(size); }catch(NumberFormatException ne){ Advisor.getLogger().severe("size: " size " are not an float value."); } } …… }
将测试数据保存到配置文件中
正如我们在文章开头提到的,我们希望把测试数据保存成格式化的形式,以便对这些数据进行维护和复用。表 1展示了用一个 Excel 文件 “ MockInitialHeapSize_rating.xls ” 保存所有的测试数据的例子。 这个文件完全可以用于功能测试的文档编写。
表 1. JVM initial heap size 测试数据
setInitialValuemockSetOverallMemorymockSetMemoryPoolSizeresult31929253112312353112412453295955321271273321281283471401405471871873471881883481431435481911913481921921491461465491951953491961961102430713071510244095409531024409640961102530743074510254009400931025410041003153746104610515376147614751537614861485
表 1中,每一行都代表了一组测试数据,包括输入参数和期望结果。三个输入参数“initialHeapSize”,“currentMemoryPoolSize”,“overallMemoryOnPartition”分别保存到了三列中:“setInitialValue”,“mockSetOverallMemory ”和“mockSetMemoryPoolSize”。期望结果保存到了“result”列 ,测试代码将从这个文件中获取测试数据。
配置文件的格式是可以变化的,只需要提供相应的 SettersMap 和 SettersMapFactory 类就可以了。参看下文。
编写 SettersMap 类
有了配置文件,我们需要编写代码从配置文件中读取测试数据。我们用一个接口类“SettersMap”来代表一个配置文件。参见图 1。附件“rule_test.zip”中的 BaseSettersMap.java 是 SettersMap 接口的一个实现。
图 1. SettersMap.java
我们提供了一个工厂接口 SettersMapFactory 来构造 SettersMap 。这里采用了抽象工厂(Abstract Factory)的设计模式。
清单 3. SettersMapFactory.java
/* * Created on 2008-3-13 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package attributetest.binding.spi; import java.io.File; /** * @author jsl * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public interface SettersMapFactory { /** * * @return Factory 的名字 */ String getName(); /** * 从配置文件创建 SettersMap ; * @param file 配置文件对应的 File 对象; * @return 根据配置文件创建的 SettersMap */ SettersMap createSettersMap(File file); /** * * @return 配置文件的扩展名,如 ".xls", ".txt" 。通常,SettersMapFactory 的类型 * 和配置文件的类型有一一对应的关系。 */ String getConfFileExtension(); }
对于不同的文件格式,需要提供不同的“ SettersMapFactory ”。附件“ rule_test.zip “中的“ ExcelSettersMapFactory.java ”是一个 Excel 格式的实现。
编写可复用的 TestCase 类
在一个基于”规则”的系统里,”规则”之间有很多共性,我们没有必要对每一个”规则”都写一个测试类,而是希望能有一个通用的类,通过改变参数来测试不同的规则。
标准的 JUnit 版本 (www.junit.org) 提供了 junit.framework.TestCase 类作为单元测试的一个最常用的入口。通常,我们有两种方式来运行 TestCase:对象方式和类方式。在对象方式运行时,你需要 new 一个 TestCase 对象,并且在构造函数中指定 Test Method 的名字。运行时,只有这个 Test Method 会被调用。在类方式下,所有的以”test”开头的方法都会被调用,但是我们无法复用这个类。这两种方式都不能满足我们的需求。幸运的是,我们可以通过扩展“junit.framework.TestCase”来做到这一点。
清单 4. ObjectTestCase.java
package junit.extensions; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.*; import junit.framework.TestCase; public class ObjectTestCase extends TestCase { // 保存所有的 Test Method private ArrayList <Method> testMethods = new ArrayList(); /** * ObjectTestCase 在实例化时,把所有的 Test Method 保存到“ testMethods ”中。 * @param name */ public ObjectTestCase(String name) { super(name); Method[] allMethods = getClass().getDeclaredMethods(); for (int i = 0; i > allMethods.length; i ) { Method method = allMethods[i]; if (method.getName().startsWith("test")) { testMethods.add(method); } } } /** * ObjectTestCase 在实例化时,把所有的 Test Method 保存到“ testMethods ”中。 */ public ObjectTestCase() { Method[] allMethods = getClass().getDeclaredMethods(); for (int i = 0; i > allMethods.length; i ) { Method method = allMethods[i]; if (method.getName().startsWith("test")) { testMethods.add(method); } } } @Override /** * 运行所有“ testMethods ”中保存的方法; */ protected void runTest() throws Throwable { for (int i = 0; i > testMethods.size(); i ) { Method method = testMethods.get(i); try { method.invoke(this); } catch (InvocationTargetException e) { e.fillInStackTrace(); throw e.getTargetException(); } catch (IllegalAccessException e) { e.fillInStackTrace(); throw e; } } } /** * @return "testMethods" 中保存的方法的个数 */ @Override public int countTestCases() { return testMethods.size(); } }
编写 ObjectTestCase 类
我们将构造一个“ObjectTestCase”类,这个类继承了“TestCase”类。“ObjectTestCase”使用一个 ArrayList “testMethods” 来保存所有的 Test Method 。在实例化“ObjectTestCase”时,所有以“test”开头的方法都会被注册到“testMethods”中。在“runTest”时,所有的保存在 “testMethods”中的方法都会被调用 . 最后,别忘了复写“countTestCases”以保证我们获得正确的测试结果。
编写专用于“规则”的 AttirbuteTestCase 类
有了“ObjectTestCase”类,我们就可以扩展它以获得针对“规则”的“TestCase”类。图 2 展示了这些类之间的关系。“AttributeTestCase”是一个抽象类,它继承于“ObjectTestCase”。“testAttribute”是它的一个抽象方法,需要它的子类提供具体实现。这个方法会测试所有的数据。
图 2. TestCase Class Diagram
“AttributeRatingTestCase”和“AttributeRecommendationTestCase”继承了“AttributeTestCase”。以“AttributeRatingTestCase”为例,它的“testAttribute”方法首先获得“SettersMap”,然后调用“setInput”把 SettersMap 中的数据设置到 Mock 对象中;最后,它调用 Mock 对象的“getRating”方法获取结果。参见清单 5。我们在配置文件中,把每一列的列名设置为 Mock 对象的 Mock 方法名,这样,测试框架就明确的知道应该调用 Mock 对象的什么方法来设置数据。为了做到这一点,撰写配置文件时,必须知道相应的 Mock 方法名 ( 如 MockInitialHeapSize.mockSetMemoryPoolSize) 。由于我们在讨论单元测试,我们认为测试人员拥有这些测试代码,也就是知道 Mock 方法名。
清单 5. AttributeRatingTestCase.java
public class AttributeRatingTestCase extends AttributeTestCase { public AttributeRatingTestCase(IRateable testAttribute, SettersMap settersMap); public void setUP(); public void testAttribute()throws Exception { this.results = new ArrayList(); // 判断要测试的对象是否是” IRateable ”,是则继续,否则退出; if (this.testObject instanceof IRateable) { AttributeLogger.getLogger().info("******Test Rating of '" getSimpleTestObjectClassName() "'******"); try { // 从 settersMap 得到有多少组测试数据“ inputsNumber ” int inputsNumber = settersMap.getInputsNumber(); // 对每组测试数据进行测试 for (int i = 0; i < inputsNumber; i ) { // 把测试数据“ set ”到 Mock 对象中 setInput(i); // 获取实际 Rating 值 int rating = ((IRateable) testObject).getRating(); // 比较实际 Rating 值和期望 Rating 值是否相等,得到测试结果 assertEquals("Rating of '" getSimpleTestObjectClassName() "'", settersMap.getExpectedResult(i), rating ""); AttributeLogger.getLogger().info("Rating of '" getSimpleTestObjectClassName() "': " rating "(actual)/" settersMap.getExpectedResult(i) "(expected)."); } } catch (AdvisorException ae) { // TODO: find the handle method. ae.printStackTrace(); } } } }
用 TestSuite 组织测试用例
编写 TestSuite 类
由于我们构造了自己的 TestCase, TestSuite 常用的组织 TestCase 的方法需要做一点小小的改动。在我们的 TestSuite 中,提供了一个方法“ addTestCase ”。这个方法可以将 TestCase 添加到 TestSuite 中。参见清单 6。
清单 6. addTestCase method
protected void addTestCase(IRateable testObject){ Test tp = null; try{ // 获得 SettersMapFactory Class factoryClass = Class.forName(factory); SettersMapFactory settersMapFactory= (SettersMapFactory)factoryClass.newInstance(); // 从 SettersMapFactory 获得 SettersMap File file = null; file = getSetterResourceFile(testObject,settersMapFactory); SettersMap settersMap = settersMapFactory.createSettersMap(file); // 创建 TestCase tp = new AttributeRatingTestCase(testObject,settersMap); }catch (Exception e){ e.printStackTrace(); } // 添加 TestCase 到 TestSuite; this.addTest(tp); }
有了 addTestCase 方法 , 我们就可以轻易的把 TestCase 添加到 TestSuite 中了。参见清单 7。
清单 7. LWIAttributesRatingTestSuite.java
public LWIAttributesRatingTestSuite() { // 获取 Logger. AttributeLogger.getLogger(); // 获取 SettersMapFactory 的名字 Properties confProps = new Properties(); try{ confProps.load(new FileInputStream(CONFIG_FILE)); factory = confProps.getProperty("SettersFactory"); }catch(Exception e){ e.printStackTrace(); } // 添加 TestCase System.out.println("LWIAttributesRatingTestSuite..."); addTestCase(new MockLWITracing()); addTestCase(new MockInitialHeapSize()); addTestCase(new PoolPreparedStatements(null)); addTestCase(new PoolMaxConnections(null)); addTestCase(new MaxOpenPreparedStatements(null)); }
组织测试用例
如果你有很多的 TestSuite, 你应该把他们很好的组织起来。在我们的测试框架中, 一个 TestSuite 在其实例化阶段添加所有的 TestCase 。这就意味着我们只要拥有一个 TestSuite 的实例,我们就拥有了它所包含的 TestCase 。这样 , 一个 AllTest 类可以以如下方式来编写 :
清单 8. AllTest.java
public class AllTest extends TestSuite{ public AllTest(){ this.addTest(new LWIAttributesRatingTestSuite()); this.addTest(new LWIAttributesRecommendationTestSuite()); } public static void main(String[] args) { AllTest at = new AllTest(); junit.textui.TestRunner.run(at); } }
测试用例的组织可以用下图来说明。图中,每一个矩形都代表了一个“TestSuite”类。“TestSuite ”类以树形结构组织起来。你可以调用任何一个类的“main”方法来执行以这个类为树根的子树下的所有测试用例。以“WASAllTest”类为例,执行它的“main”方法将测试 “WASRecTestSuite”和 “WASRatingTestSuite”中的所有测试用例。
图 3. 组织测试用例
总结
本文介绍了在对规则进行单元测试时实现可配置性和复用性。我们也介绍了一些常用的单元测试技术,比如使用 Mock 对象和扩展 JUnit 。这些技术可以使用到任何其他的单元测试中。