[英]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.