繁体   English   中英

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

[英]Trying to run retries on before() Method before failing a test

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

许多测试在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 ,请查看我如何立即重新运行失败的JUnit测试的答案 这应该做你想要的。 如果您使用该答案中定义的重试规则,如果它抛出异常,这实际上将重新执行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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM