gpt4 book ai didi

java - 如果 JUnit 测试失败,如何在 SuiteClass 中重试?

转载 作者:行者123 更新时间:2023-11-30 05:45:40 29 4
gpt4 key购买 nike

我有以下 RetryRule 类:

public class RetryRule implements TestRule {
private int retryCount;

public RetryRule(int retryCount) {
this.retryCount = retryCount;
}

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;

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.");
if (caughtThrowable != null) {
throw caughtThrowable;
}
}
};
}
}

以及以下 SuiteClass:

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({
MakeBookingTest.class,
PaymentTest.class
})

public class TestSuite {
}

这有两个测试类。MakeBookingTestPaymentTest。它们每个都有多个 JUnit 测试。

我希望在失败时重试。知道我怎样才能实现它吗?

编辑:为了更好地理解,您可以使用我的代码来举例说明要添加的内容。谢谢。欣赏它。

最佳答案

首先我同意GhostCat的观点。
Flakey 测试代码才是真正的问题。

但是,如果“不稳定”不在您的代码中(例如与外部 Web 服务的网络连接不良),那么重新运行测试可能会很有用。

在这种情况下,您可以执行以下操作。

首先创建一个接口(interface)注解。(这将用于指示哪些测试需要重试。)

@Retention(RetentionPolicy.RUNTIME)
public @interface Retry {}

然后将TestRule应用于我们的测试。(如果存在 Retry 注释,此规则将检查失败)

public class RetryRule implements TestRule {
@Override
public Statement apply(Statement base, Description method) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
try {
base.evaluate();
} catch (Throwable t) {
Retry retry = method.getAnnotation(Retry.class);
if (retry != null) {
base.evaluate();
} else {
throw t;
}
}
}
};
}
}

最后,在我们的测试中,我们将所有内容放在一起

public class RetryTest {
private static int count = 0;

@Rule
public RetryRule rule = new RetryRule();

@Test
@Retry
public void testToRetry() throws Exception {
callMyFlakeyCode();
}
}

关于java - 如果 JUnit 测试失败,如何在 SuiteClass 中重试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54883604/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com