我正在使用 JUnit 规则立即重新运行任何失败的测试。我的额外要求是,如果重新运行也失败,请确定它们是否因相同原因而失败。
为此,我改编了 this answer 中的代码记录失败并进行比较。然而,比较 (.equals) 总是评估为 false,尽管它们出于同样的原因而失败。解决此问题的最佳方法是什么?
private Statement statement(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
for (int i = 0; i < retryCount; i++) {
try {
base.evaluate();
return;
} catch (Throwable t) {
System.err.println(description.getDisplayName() + ": run " + (i + 1) + " failed");
// Compare this error with the one before it.
if (errors.size() > 0) {
if (t.equals(errors.get(errors.size() - 1))) {
System.out.println("The error is the same as the previous one!");
} else {
System.out.println("The error is different from the previous one.");
}
}
errors.add(t);
}
}
System.err.println(description.getDisplayName() + ": giving up after " + retryCount
+ " failures");
// Throw most recent error.
throw errors.get(errors.size() - 1);
}
};
}
最佳答案
如果只想知道它是否是任何类的类型,请使用 instance of
,例如:
if( t instanceof Throwable){
//...
}
关于java - 比较两个 throwable 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30260863/