【问题标题】:Trying to run retries on before() Method before failing a test在测试失败之前尝试在 before() 方法上运行重试
【发布时间】:2013-02-27 01:05:41
【问题描述】:

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

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

我已经添加了代码 sn-p 但我不确定这是最好的方法/做法...

//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();
    }

}

【问题讨论】:

  • 除了将其重构为循环而不是递归之外,您的下一个最佳选择是编写自己的测试运行器并将其与 @runwith 注释一起使用。
  • 我认为作为循环而不是递归会更好。此外,如果环境随时间变化,请考虑在循环中放置睡眠调用。

标签: java unit-testing testing junit integration-testing


【解决方案1】:

您可以为此使用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

【讨论】:

  • 您的解决方案重试测试主体。它不会以任何方式从使用 Before 注释的设置方法失败中恢复,这是实际问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-14
相关资源
最近更新 更多