4

JUnit テストを実行している不安定な ENV があります。

接続/ネットワーク/非テスト関連の問題のため、多くのテストが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();
    }

}
4

1 に答える 1

3

これには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
于 2013-03-13T04:10:01.537 に答える