2012-12-13 30 views
5

我有一個Junit測試類,其中有多個@Test方法,需要按順序運行。如果在方法中拋出異常,我想停止整個測試用例和錯誤,但所有其他測試方法正在運行。具有多個@Test方法的Junit測試類

public class{ 

@Test{ 
//Test1 method`enter code here` 
} 

@Test{ 
//Test2 method 
} 

@Test{ 
//Test3 method 
} 

} 

如果Test1的方法失敗,那麼請不要運行其他測試

注意:所有獨立測試

回答

9

單元測試應該設計成相互獨立地運行。執行順序無法保證。您應該重新設計您的測試課程,以便順序不重要。

沒有進一步的信息,很難專門爲您提供建議。但是可能有一個方法,它在運行每個測試之前檢查一些前提條件。如果您包含Assume.assumeTrue(...)方法調用,那麼如果條件失敗,您的測試可能會被跳過?

2

如果您需要保留結果並且未通過測試而不能使整組失敗,請將所有這些測試合併爲一個測試並假設測試。

8

正如描述的here,JUnit 4.11支持使用註釋@FixMethodOrder的有序執行,但其他的都是正確的,所有的測試應該是相互獨立的。

在測試結束時,您可以設置全局成功標誌。該標誌將在每次測試開始時進行測試。如果標誌在一次測試結束時沒有設置(因爲它在結束前失敗),所有其他測試也將失敗。 例子:

@FixMethodOrder(MethodSorters.NAME_ASCENDING) 
public class ConsecutiveFail{ 
    private boolean success = true; 

    @Test 
    public void test1{ 
    //fist two statements in all tests 
    assertTrue("other test failed first", success); 
    success = false; 
    //do your test 
    //... 

    //last statement 
    success = true; 
    } 

    @Test 
    public void test2{ 
    //fist two statements in all tests 
    assertTrue("other test failed first", success); 
    success = false; 
    //do your test 
    //... 

    //last statement 
    success = true; 
    } 
} 
1

這裏的例子爲TestNG的如何指定測試運行命令:

@Test(priority = 1) 
public void test1(){} 

@Test(priority = 2) 
public void test2(){} 

@Test(priority = 3) 
public void test3(){}