zoukankan      html  css  js  c++  java
  • junit模板方法模式应用

    模板方法模式

    定义

      定义一个操作中的算法骨架,而将一些步骤延伸到子类中去,使得子类可以不改变一个算法的结构,即可重新定义该算法的某些特定步骤。这里需要复用的是算法的结构,也就是步骤,而步骤的实现可以在子类中完成;

    构成

      父类角色:提供模板;

      子类角色:为模板提供实现;

    java代码实现

    public abstract class Template {
    
        //定义执行步骤,每个步骤的具体实现由子类完成
        public void method() {
            this.step1();
            this.step2();
            this.step3();
        }
    
        protected abstract void step1();
    
        protected abstract void step2();
    
        protected abstract void step3();
    }
    public class ConcreteTemplate extends Template {
    
        @Override
        protected void step1() {
            System.out.println("ConcreteTemplate.step1()");
        }
    
        @Override
        protected void step2() {
            System.out.println("ConcreteTemplate.step2()");
        }
    
        @Override
        protected void step3() {
            System.out.println("ConcreteTemplate.step3()");
        }
    }
    public class Client {
        public static void main(String[] args) {
            Template template = new ConcreteTemplate();
            template.method();
        }
    }

    模板模式在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框架仅负责算法的轮廓和骨架而开发人员则负责给出这个算法的各个逻辑步骤

  • 相关阅读:
    《人月神话》读后感
    十天冲刺计划(第二次)
    日历表的事件处理和管理(刘静)
    十天冲刺计划
    结组开发项目(TD学生助手)
    电梯调度(二)
    敏捷软件开发方法综述
    对于二维数组求子数组的和的最大值
    电梯调度(一)
    FloatyFish休闲游戏 Beta正式发布
  • 原文地址:https://www.cnblogs.com/luogankun/p/3996304.html
Copyright © 2011-2022 走看看