我正在使用 JUnit 4.10 来运行测试套件,并且按照 Matthew Farwell 在如何立即重新运行失败的 JUnit 测试? https://stackoverflow.com/questions/8295100/how-to-re-run-failed-junit-tests-immediately邮政。我使用以下代码创建了一个“RetryTestRule”类:
public class RetryTestRule implements TestRule {
private final int retryCount;
public RetryTestRule(int retryCount) {
this.retryCount = retryCount;
}
@Override
public Statement apply(Statement base, Description description) {
return statement(base, description);
}
private Statement statement(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
Throwable caughtThrowable = null;
// retry logic
for (int i = 0; i < retryCount; i++) {
try {
base.evaluate();
return;
} catch (Throwable t) {
caughtThrowable = t;
System.err.println(description.getDisplayName() + ": run " + (i + 1) + " failed");
}
}
System.err.println(description.getDisplayName() + ": Giving up after " + retryCount
+ " failures");
throw caughtThrowable;
}
};
}
}
当在测试用例中使用它作为规则时,它工作得很好,但在套件的每个测试用例中使用 @Rule 符号而不是套件定义中的单个符号似乎不是最佳选择,所以在检查了一点之后,我尝试了我的 Suite 类中的新 @ClassRule 表示法:
@RunWith(Suite.class)
@SuiteClasses({
UserRegistrationTest.class,
WebLoginTest.class
})
public class UserSuite {
@ClassRule
public static RetryTestRule retry = new RetryTestRule(2);
}
问题是这不能按预期工作:失败的测试不会被重试。有没有人尝试过这个并知道解决方案?非常感谢帮助!
@ClassRule
每个类执行一次,而不是每个方法执行一次。要让每个方法执行一次,您需要使用@Rule
就像你正在做的那样,或者按照答案如何在套件中定义JUnit方法规则? https://stackoverflow.com/questions/7639353/how-to-define-junit-method-rule-in-a-suite/7653558#7653558.
要重用现有规则,您可以使用以下命令将规则添加到要运行的规则列表中:RunRules
类如下:
public class MyRunner extends BlockJUnit4ClassRunner {
public MyRunner(Class<?> klass) throws InitializationError {
super(klass);
}
@Override
protected void runChild(final FrameworkMethod method, RunNotifier notifier) {
Description description= describeChild(method);
if (method.getAnnotation(Ignore.class) != null) {
notifier.fireTestIgnored(description);
} else {
RunRules runRules = new RunRules(methodBlock(method), Arrays.asList(new TestRule[]{new RetryTestRule(3)}), description);
runLeaf(runRules, description, notifier);
}
}
}
这是使用上面答案中的示例。您也可以将这两个答案结合起来以进行更细粒度的控制,例如,如果您的测试中有注释,则创建一个 RetryTestRule。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)