JUnit源代码中Proctectable接口的含义是什么?
问题描述:
我最近在深入挖掘JUnit-4.11
的源代码,让我困惑的是看似多余的Protectable
接口。声明如下:JUnit源代码中Proctectable接口的含义是什么?
public interface Protectable {
public abstract void protect() throws Throwable;
}
在TestResult
类,有一个void run(final TestCase test)
方法,其中,如下一个匿名Protectable
实例实现:
protected void run(final TestCase test) {
startTest(test);
Protectable p = new Protectable() {
public void protect() throws Throwable {
test.runBare();
}
};
runProtected(test, p);
endTest(test);
}
runProtected
方法如下:
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);
}
}
正如我们所看到的,runProtected
所做的只是执行test.runBare();
,所以我对Protectable接口的存在有什么意义?为什么我们不能像以下编写代码?
protected void run(final TestCase test) {
startTest(test);
test.runBare();
endTest(test);
}
答
要回答你的最后一个问题首先,你不能使用
protected void run(final TestCase test) {
startTest(test);
test.runBare();
endTest(test);
}
因为它不会做你想做的。 JUnit使用异常来管理断言,具体为AssertionFailedError
。因此,当两个值不相等时,Assert.assertEquals()
将引发一个AssertionFailedError
。因此,在上述方法中,如果断言失败,则不会调用endTest(test)
,这意味着正确的事件(测试的失败/错误)不会被触发,并且tearDown()
将不会被执行。
Protectable
接口在那里为跑步者提供了一个更通用的界面,因此您不必将TestCase
交给该方法,以允许执行不同的操作。
另外,这是包junit.framework.*
,它是JUnit 3的一部分.JUnit 4是它所在的位置,如果您想了解,请在org.junit.*
包中查看更多内容。
答
似乎来处理特定的方式抛出的异常: 呼叫addFailure
的断言异常(测试失败),addError
其他异常(你的测试不能很好地编码)