我最近在研究 的源代码JUnit-4.11,让我感到困惑的是看似多余的Protectable接口。声明如下:
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);
}