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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值