TestResult
TestResult 有两个 List,用来记录 Exception 和 Failure。捕获 runBare() 抛出的 Exception,首先判断是否为 AssertionFailedError,是则调用 addFailure() 把,把异常加到 fFailures。否则则并调用 addError() 方法,把异常加到 fErrors 中。
catch (AssertionFailedError e) {
addFailure(test, e);
}
catch (ThreadDeath e) { // don't catch ThreadDeath by accident
throw e;
}
catch (Throwable e) {
ddError(test, e);
}
TestListener
前面提到 result 加上了一个 ResultPrinter,ResultPrinter 会记录运行中的所有 Exception,并且实时地以不同的格式输出。当所有的 Test 都运行完毕后,ResultPrinter 会对 result 进行分析,首先输出运行的时间,接着 printError() 输出 fErrors 的个数,printFailures() 则输出 fFailures 的个数。PrintFooter() 根据 result.wasSuccessful(),如果成功,则打印 OK 和 test 运行的总次数,如果失败,则打印出 test 总的运行的个数,失败和错误的个数。
参数一的统计输出结果:
Time: 0.016
There was 1 failure:
1) testPay(TestShoppingCart)junit.framework.AssertionFailedError:
expected:<30> but FAILURES!!!
Tests run: 2, Failures: 1, Errors: 0
清单一:
Java代码
synchronized void print(TestResult result, long runTime) {
printHeader(runTime);
printErrors(result);
printFailures(result);
printFooter(result);
}
清单二:
Java代码
protected void printFooter(TestResult result) {
if (result.wasSuccessful()) {
getWriter().println();
getWriter().print("OK");
getWriter().println (" (" + result.runCount() + " test"
+ (result.runCount() == 1 ? "": "s") + ")");
} else {
getWriter().println();
getWriter().println("FAILURES!!!");
getWriter().println("Tests run: "+result.runCount()+
", Failures: "+result.failureCount()+
", Errors: "+result.errorCount());
}
getWriter().println();
}
完整生命周期
整个生命周期将在下图显示: