首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

不使用TestNG重试测试用例

在不使用TestNG的情况下重试测试用例,您可以使用JUnit框架结合自定义的重试逻辑来实现

  1. 首先,确保您的项目中已经添加了JUnit依赖。如果您使用Maven,可以在pom.xml文件中添加以下依赖:
代码语言:javascript
复制
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
</dependency>
  1. 创建一个自定义的测试运行器,用于在测试失败时重试:
代码语言:javascript
复制
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来监听测试失败事件。当测试失败时,我们会检查重试次数是否小于最大重试次数,如果是,则重新运行失败的测试。

  1. 在您的测试类上使用自定义的运行器:
代码语言:javascript
复制
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);
    }
}
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

1分37秒

C语言 | 三目运算判断大写

领券