zoukankan      html  css  js  c++  java
  • JUnit中使用到的设计模式

    1.JUnit在TestCase中应用了模板方法模式:
    public void runBare() throws Throwable{
       setUp();
       try{
          runTest();
       }finally{
          tearDown();
       }
    }

    2.JUnit在TestCase类中应用了适配器(Adapter)模式:

    public void runBare()throws Throwable {
         Throwable exception = null;
         setUp();

         try {
              runTest();
        } catch (Throwable running) {
              exception = running;
        } finally {
             try {
                  tearDown();
             } catch (Throwable tearingDown) {
                 if (exception == null)

              exception = tearingDown;
             }
         }
        if (exception == null) return;

       throw exception;
    }


    在runBare()方法中,通过runTest()方法将我们自己编写的testXXX()方法进行了适配,使得JUnit可以执行我们自己编写的TestCase,runTest方法实现如下:

    protected void runTest()throws Throwable{
        assertNotNull(this.fName);

          Method runMethod = null;
        try {
            runMethod = super.getClass().getMethod(this.fName, (Class[])null);
         } catch (NoSuchMethodException e) {
             fail("Method \"" + this.fName + "\" not found");
        }
        if (!(Modifier.isPublic(runMethod.getModifiers()))) {
          ("Method \"" + this.fName + "\" should be public");
        }

        try{
          runMethod.invoke(this, (Object[])new Class[0]);
         } catch (InvocationTargetException e) {
              e.fillInStackTrace();
               throw e.getTargetException();
           } catch (IllegalAccessException e) {
              e.fillInStackTrace();
              throw e;
         }
    }

    3.观察者模式
    /**
     * A Listener for test progress
     */
    public interface TestListener {
     /**
       * An error occurred.
       */
     public void addError(Test test, Throwable t);
     /**
       * A failure occurred.
       */
      public void addFailure(Test test, AssertionFailedError t); 
     /**
      * A test ended.
      */
      public void endTest(Test test);
     /**
      * A test started.
      */
     public void startTest(Test test);
    }

    4.命令模式(Command)

    经过使用Command后的给系统的架构效果:
    Command模式将实现请求的一方(TestCase开发)和调用一方(JUnit)进行解藕
    Command模式使新的TestCase很容易加入,无需改变已有的类,只需继承TestCase类即可
    Command模式可以将多个TestCase进行组合成一个复合命令产,TestSuite就是它的一个复合命令,当然它使用了Composite模式
    Command模式容易反请求的TestCase组合成请求队列,这样使接收请求的一方(JUnit Framwork),容易决定是否执行请求,一旦发现测试用命失败或者错误可以立该停止进行报告。

    5.装饰模式

    6.组合模式(Composite)

  • 相关阅读:
    mysql基础(三)
    mysql基础(二)
    Mysql基础(一)
    Less32-Less-33
    Less-27
    Less-26
    Less-25
    Less-23
    Less18-Less19
    Less13-Less-14
  • 原文地址:https://www.cnblogs.com/mingforyou/p/2287716.html
Copyright © 2011-2022 走看看