2013-03-11 60 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