模板模式在junit3中的应用
查看TestCase.java源代码
public abstract class TestCase extends Assert implements Test { public void runBare() throws Throwable { setUp(); try { runTest(); } finally { tearDown(); } } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } protected void runTest() throws Throwable { assertNotNull(fName); Method runMethod= null; try { runMethod= getClass().getMethod(fName, null); //null表示测试方法必须是无参的 } catch (NoSuchMethodException e) { fail("Method \""+fName+"\" not found"); } if (!Modifier.isPublic(runMethod.getModifiers())) { fail("Method \""+fName+"\" should be public"); //明确表示测试方法必须是public修饰的 } runMethod.invoke(this, new Class[0]); } } |
在TestCase.java中的runBare()方法中定义了测试方法的执行步骤:setUp()-->runTest()-->tearDown(); 具体方法的真正实现推迟到子类中去实现。
junit3中引入模板方式模式的好处:
1)将各个测试用例中的公共的行为(初始化信息和释放资源等)被提取出来,可以避免代码的重复,简化了测试人员的工作;
2)在TestCase中实现一个算法的不变部分,并且将可变的行为留给子类来实现。增强了系统的灵活性。使JUnit框架仅负责算法的轮廓和骨架,而开发人员则负责给出这个算法的各个逻辑步骤。