在不使用TestNG的情况下重试测试用例,您可以使用JUnit框架结合自定义的重试逻辑来实现
pom.xml
文件中添加以下依赖:<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
import org.junit.runner.Description;
import org.junit.runner.Runner;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;
public class RetryRunner extends BlockJUnit4ClassRunner {
private static final int MAX_RETRIES = 3;
public RetryRunner(Class<?> klass) throws InitializationError {
super(klass);
}
@Override
protected void runChild(FrameworkMethod method, RunNotifier notifier) {
Description description = describeChild(method);
RunListener listener = new RunListener() {
int retryCount = 0;
@Override
public void testFailure(Failure failure) throws Exception {
if (retryCount < MAX_RETRIES) {
retryCount++;
System.out.println("Retrying test: " + description.getDisplayName() + " (attempt " + retryCount + ")");
runChild(method, notifier);
} else {
notifier.fireTestFailure(failure);
}
}
};
notifier.addListener(listener);
super.runChild(method, notifier);
}
}
在这个自定义运行器中,我们重写了runChild
方法,并添加了一个RunListener
来监听测试失败事件。当测试失败时,我们会检查重试次数是否小于最大重试次数,如果是,则重新运行失败的测试。
import org.junit.Test;
import static org.junit.Assert.assertEquals;
@RunWith(RetryRunner.class)
public class MyTestClass {
@Test
public void testAddition() {
assertEquals(2, 1 + 1);
}
@Test
public void testSubtraction() {
assertEquals(0, 1 - 1);
}
}
领取专属 10元无门槛券
手把手带您无忧上云