2013-03-11 109 views
3

我有一个不稳定的ENV其即时通讯上尝试)未能通过测试

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

伊夫添加的代码片段但林不知道这是最好的方法/做法这么做之前...

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

} 
+1

除了重构这是一个循环,而不是递归,你的下一个最好的选择是编写你自己的测试运行器,并使用@runwith注解。 – radai 2013-03-11 18:19:50

+0

我认为这会更好地做一个循环,而不是递归。另外,如果环境随时间变化,请考虑在循环中添加睡眠呼叫。 – 2013-03-11 18:46:04

回答

4

你可以用这个TestRule,请看我的回答How to Re-run failed JUnit tests immediately?。这应该做你想做的。如果您使用的是答案中定义的重试规则,这实际上之前重新执行(),如果它抛出一个异常:

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