我失败的Junit测试重新运行一次并停止,但我希望它运行3次。我想我的注释在某种程度上被搞砸了。请问注释的正确格式是什么。注意:我还要了解有关测试SuiteClasses的正确注释的信息。以下是我的注释
@Rule
public Retry retry = new Retry(3);
任何帮助将不胜感激
public class HostTest {
/**
* Test method for {@link com.ibm.ws.ui.collective.internal.rest.resource.Host}.
*/
public class RetryTest {
/**
* @param i
*/
public RetryTest(int i) {
// TODO Auto-generated constructor stub
}
public class Retry extends TestRule {
private final int retryCount;
public Retry(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;
// implement retry logic here
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;
}
};
}
}
}
@Test
public void sanityCheck_withHostPathsNull() {
Host h = new Host("myHost");
Map<String, Object> mapFromController = new HashMap<String, Object>();
h.setHostPaths(mapFromController);
assertFalse("it is not empty", h.getHostPaths().isEmpty());
}
}
答案 0 :(得分:1)
您确定失败的测试只运行一次吗?您可能需要使用计数器或打印语句进行确认。
我不确定你认为Retry
规则会做什么,但是这段代码:
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");
}
}
表示只有在抛出任何内容时才会重试测试(意味着测试失败)。因此,Retry(3)
表示运行每个测试,如果有任何失败,则尝试再次运行失败的测试2次以查看它是否最终通过。如果在最终重试之后,如果它仍然失败,则重新抛出最终失败消息,这将导致测试失败。
如果您想要反复重试测试,即使测试通过,那么您应该摆脱for循环中的return
语句。但是你必须要小心,如果它不是空的,你只能在最后重新抛出throwable。 (意思是如果测试最后一次通过则不要扔)
要使测试反复运行,无论它是否通过:
@Override
public void evaluate() throws Throwable {
Throwable caughtThrowable = null;
// implement retry logic here
for (int i = 0; i < retryCount; i++) {
try {
base.evaluate();
} catch (Throwable t) {
caughtThrowable = t;
System.err.println(description.getDisplayName() + ": run " + (i + 1) + " failed");
}
}
if(caughtThrowable !=null){
System.err.println(description.getDisplayName() + ": giving up after " + retryCount + " failures");
throw caughtThrowable;
}
}