OK,前面的博客我们整理了junit运行完了所有的测试用例,那么OK了,现在开始该收集测试结果了。
在这最后一步中,junit主要是玩一个类,TestResult。这里类中封装了几个参数,在初始化这个类的时候赋初始值:
protected List<TestFailure> fFailures; // 失败结果集
protected List<TestFailure> fErrors; // 错误结果集
protected List<TestListener> fListeners; // 测试监听
protected int fRunTests; // 执行的测试的数量
private boolean fStop; // 是否停止,开关
public TestResult()
{
fFailures = new ArrayList<TestFailure>();
fErrors = new ArrayList<TestFailure>();
fListeners = new ArrayList<TestListener>();
fRunTests = 0;
fStop = false;
}
/**
* @创建时间: 2016年1月21日
* @相关参数: @param test
* @相关参数: @param p
* @功能描述: 运行一个用例
*/
public void runProtected(final Test test, Protectable p)
{
try
{
p.protect();
}
catch (AssertionFailedError e)
{
addFailure(test, e);
}
catch (ThreadDeath e)
{ // don't catch ThreadDeath by accident
throw e;
}
catch (Throwable e)
{
addError(test, e);
}
}
这里的try块触发测试用例的执行,然后2个catch块来捕获异常。如果抛出了AssertionFialedError异常,那么就说明我们的语言失败了,然后添加到TestResult类的失败结果集中,如果抛出了其他异常,那么就是说我们编写的测试代码报错了,然后添加到TestResult类的错误结果集中。JUnit 执行测试方法,并在测试结束后将失败和错误信息通知给所有的 test listener 。其中 addFailure、addError、endTest、startTest 是 TestListener 接口的四大方法,而 TestListener 涉及到 Observer 设计模式。
/**
* @创建时间: 2016年1月21日
* @相关参数: @param test 测试用例
* @相关参数: @param e 异常
* @功能描述: 往失败List中添加失败
*/
public synchronized void addFailure(Test test, AssertionFailedError e)
{
fFailures.add(new TestFailure(test, e));
for (TestListener each : cloneListeners())
{
each.addFailure(test, e);
}
}
上面的代码不多分析了,又是观察者模式来开始通知TestResult类上注册的监听器。在Junit38中往TestResult类中默认添加的监听其实就一个ResultPrinter类。
TestResult 的 addFailure 进一步调用 ResultPrinter 的 addFailure。
@Override
public void addError(Test test, Throwable e)
{
getWriter().println("KAO,有报错啦!!!");
}
@Override
public void addFailure(Test test, AssertionFailedError t)
{
getWriter().println("KAO,有失败啦");
}
此处代码