【发布时间】: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