什么';JUnit源代码中可编程接口的含义是什么?
我最近在深入研究JUnit-4.11的源代码,让我感到困惑的是看似冗余的可保护的接口。声明如下:什么';JUnit源代码中可编程接口的含义是什么?,junit,junit4,Junit,Junit4,我最近在深入研究JUnit-4.11的源代码,让我感到困惑的是看似冗余的可保护的接口。声明如下: public interface Protectable { public abstract void protect() throws Throwable; } protected void run(final TestCase test) { startTest(test); Protectable p = new Protectable() { pub
public interface Protectable {
public abstract void protect() throws Throwable;
}
protected void run(final TestCase test) {
startTest(test);
Protectable p = new Protectable() {
public void protect() throws Throwable {
test.runBare();
}
};
runProtected(test, p);
endTest(test);
}
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);
}
}
在TestResult
类中,有一个void run(final TestCase test)
方法,其中实现了一个匿名Protectable
实例,如下所示:
public interface Protectable {
public abstract void protect() throws Throwable;
}
protected void run(final TestCase test) {
startTest(test);
Protectable p = new Protectable() {
public void protect() throws Throwable {
test.runBare();
}
};
runProtected(test, p);
endTest(test);
}
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
方法如下:
public interface Protectable {
public abstract void protect() throws Throwable;
}
protected void run(final TestCase test) {
startTest(test);
Protectable p = new Protectable() {
public void protect() throws Throwable {
test.runBare();
}
};
runProtected(test, p);
endTest(test);
}
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()代码>,那么可保护接口的存在有什么意义吗?为什么我们不能像下面这样编写代码呢
protected void run(final TestCase test) {
startTest(test);
test.runBare();
endTest(test);
}
它似乎以特定的方式处理抛出的异常:
调用addFailure
以获取断言异常(您的测试失败),调用addError
以获取其他异常(您的测试未正确编码)首先回答最后一个问题,您不能使用
protected void run(final TestCase test) {
startTest(test);
test.runBare();
endTest(test);
}
因为它不会做你想做的事。JUnit使用异常管理断言,特别是AssertionFailedError
。因此,当两个值不相等时,Assert.assertEquals()
抛出一个AssertionFailedError
。因此,在上面的方法中,如果断言失败,则不会调用endTest(test)
,这意味着不会触发正确的事件(测试失败/错误),也不会执行tearDown()
Protectable
接口为运行程序提供了一个更通用的接口,这样您就不必将TestCase
交给该方法来允许不同的操作
另外,这是junit.framework.*
包的一部分,即JUnit3。JUnit4就是它所处的位置,如果您想学习,请查看org.JUnit.
包中的更多内容。此接口通过添加可丢弃性来保护测试用例。
因此junit可以安全地运行任何测试用例
The Throwable class is the superclass of all errors and exceptions in the Java language.