java - 在测试失败之前尝试在 before() 方法上运行重试

标签 java unit-testing testing junit integration-testing

我有一个不稳定的环境,我正在运行 JUnit 测试。

许多测试在 before() 方法上失败,因为连接/网络/非测试相关问题,我想添加一个重试 before 方法的功能 - 在测试完全失败之前。

我已经添加了代码片段,但我不确定这是这样做的最佳方式/实践...

//hold the max number of before attempts
final private int retries = 3;
//will count number of retries accrued
private int retrieCounter = 0 ;

@Before
public void before() {
    try {
        //doing stuff that may fail due to network / other issues that are not relevant to the test
        setup = new Setup(commonSetup);
        server = setup.getServer();
        agents = setup.getAgents();
        api = server.getApi();
        setup.reset();
    }
    //if before fails in any reason
    catch (Exception e){
        //update the retire counter
        retrieCounter++;
        //if we max out the number of retries exit with a runtime exception
        if (retrieCounter > retries)
            throw new RuntimeException("not working and the test will stop!");
        //if not run the before again
        else this.before();
    }

}

最佳答案

您可以使用 TestRule为此,请看我对How to Re-run failed JUnit tests immediately?的回答。 .这应该做你想做的。如果您使用该答案中定义的重试规则,这实际上会在抛出异常时重新执行 before():

public class RetryTest {
  @Rule
  public Retry retry = new Retry(3);

  @Before
  public void before() {
    System.err.println("before");
  }

  @Test
  public void test1() {
  }

  @Test
  public void test2() {
      Object o = null;
      o.equals("foo");
  }
}

这会产生:

before
test2(junit_test.RetryTest): run 1 failed
before
test2(junit_test.RetryTest): run 2 failed
before
test2(junit_test.RetryTest): run 3 failed
test2(junit_test.RetryTest): giving up after 3 failures
before

关于java - 在测试失败之前尝试在 before() 方法上运行重试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15345634/

相关文章:

node.js - 使用 Mocha 进行测试之前清除集合

python - 使用两个不同的 pytest 装置运行测试

javascript - WebDriver:更改事件未触发

unit-testing - 单元测试中必须 "provoke"才能出错的东西的正确名称是什么?

java - 使用 2 次递归调用解析堆栈

JavaFX Image取消后台加载

java - 是什么让我的代码使用这么多内存?

java - 尝试将 hashmap getValue() 解析为 int 时出错

unit-testing - AngularJS - 基本的注入(inject)测试

c# - 对上传文件的 Web API 端点进行单元测试