JUnit4源码分析(TestResult)

本文详细分析了JUnit4中的TestResult类,包括其成员变量fFailures、fErrors和fListeners,以及构造函数和相关方法。重点讲解了如何记录测试失败和错误,以及如何与测试监听器交互,最后探讨了run函数的调用过程及其在TestCase中的应用。

上一章中介绍了TestCase类中成员变量及成员函数,本章介绍TestResult类

先介绍下TestResult类:
成员变量:

 protected List<TestFailure> fFailures;
 protected List<TestFailure> fErrors;
 protected List<TestListener> fListeners;
 protected int fRunTests;
 private boolean fStop;

fFailures:记录测试失败
fErrors:记录测试错误
fListeners:记录测试监听器

构造函数:
public TestResult()

方法:

新增、删除、拷贝监听器:

public synchronized void addListener(TestListener listener);
public synchronized void removeListener(TestListener listener);
private synchronized List<TestListener> cloneListeners();

新增测试失败、新增测试错误、测试错误个数、:

 public synchronized void addError(Test test, Throwable t);
 public synchronized void addFailure(Test test, AssertionFailedError t);
 public synchronized int errorCount();

测试失败结果、测试错误存储为枚举类型:

 public synchronized Enumeration<TestFailure> failures();
 public synchronized Enumeration<TestFailure> errors();

运行测试用例:
run函数如何被调用,在前一章节TestCase类中:
TestCase类中有一部份代码如下,即运行测试用例并保存结果至TestResult:

 public TestResult run()
  {
    TestResult result = createResult();
    run(result);
    return result;
  }

  public void run(TestResult result)
  {
    result.run(this);
  }  

以下即为result.run(this)具体实现代码:

    protected void run(TestCase test)
  {
    startTest(test);
    //开始测试,具体实现代码
    **************** startTest(test)****************
      public void startTest(Test test)
  {
    int count = test.countTestCases();
    synchronized (this) {
      this.fRunTests += count;
    }
    for (TestListener each : cloneListeners())
      each.startTest(test);
  }
   *************** startTest(test)*****************

    //以下是匿名内部类,变量P指向一个实现了 Protectable 接口的匿名类的实例
    Protectable p = new Protectable() {
      public void protect() throws Throwable {
        test.runBare();//调用TestCase类中的方法
      }
    };

    runProtected(test, p);
**************runProtected(test, p)具体实现代码***********
public void runProtected(Test test, Protectable p)
  {   p.protect();  }
********************************************************
    endTest(test);
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值