I have an unstable ENV which im running JUnit tests on.
Many tests fails on before()
method because connection/network/non test related issues and I want to add a feature that retries a before method - before failing the test completely.
I've added the code snippet but im not sure this is the best way/practice to do so...
//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();
}
}
You can use a TestRule for this, please look at my answer to How to Re-run failed JUnit tests immediately? . This should do what you want. If you use the Retry rule defined in that answer, this will actually re-execute the before() if it throws an exception:
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");
}
}
This produces:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.