2017-03-04 21 views
3

我有其具有以下結構在JUnit

TestClass1 
     - testmethod1() 
     - testmethod2() 
     - testmethod3() 
     - testmethod4() 
TestClass2 
      - testmethod11() 
      - testmethod22() 
      - testmethod33() 
      - testmethod44() 

在上述結構I中要執行的testmethod4()作爲最終一個測試套件的測試套件執行順序。即)最後執行。 有一個註釋@FixMethodOrder,它執行一個方法,而不是測試類。是否有任何機制來維護測試課堂和測試方法的秩序?使用@FixMethodOrder,我可以通過重命名測試方法的名稱來執行該方法,但我無法指示junit執行測試類作爲最後一個(最後一個)。

+7

你不應該在意測試順序。如果它很重要,那麼測試之間就存在着相互依存關係,所以你正在測試行爲+相互依賴關係,而不僅僅是行爲。以任何順序執行時,您的測試應以相同的方式工作。 –

+0

我的場景是特定的方法正在訪問更新db中的值。在此之前,我需要執行所有的測試。我同意你的觀點,但你能否告訴我是否還有其他可能性? – Shriram

+0

@Shriram如果我沒有得到你的錯誤。您需要在所有其他測試類之後執行'TestClass1',然後確保最後執行'testmethod4'來執行? – nullpointer

回答

4

雖然再次引用@Andy -

你不應該在乎的測試順序。如果它很重要,那麼測試之間就會產生相互依賴關係,因此您正在測試行爲+ 相互依賴性,而不僅僅是行爲。以任何順序執行時,您的測試應以相同的方式運行 。

但如果需要的話的話,你可以嘗試Suite

@RunWith(Suite.class) 

@Suite.SuiteClasses({ 
     TestClass2.class, 
     TestClass1.class 
}) 
public class JunitSuiteTest { 
} 

在那裏你可以指定

@FixMethodOrder(MethodSorters.NAME_ASCENDING) 
public class TestClass1 { 

    @AfterClass 
    public void testMethod4() { 

,然後小心命名方法testMethod4這樣在最後執行,或者您也可以使用@AfterClass,在Junit5中很快可以用@AfterAll代替。

做看看Controlling the Order of the JUnit test by Alan Harder

+0

非常好。 – Shriram

+0

@Shriram歡迎:) – nullpointer

0

@shiriam@Andy Turner已經指出的那樣,在運行測試時,你的測試順序不應該進來的問題。

如果您在執行任何測試之前想要執行的例程,可以在其中一個類中使用靜態代碼塊。

想的東西是這樣的:

class TestBootstrap { 
    // singleton instance 
    private static final instance; 
    private boolean initialized; 

    private TestBootstrap(){ 
     this.initialized = false;  
    } 

    public static TestBootstrap getInstance(){ 
     if (instance == null){ 
      instance = new TestBootstrap() 
     } 

    } 
    public void init(){ 
     // make the method idempotent 
     if (!initialzed){ 
     // do init stuff 
     initialized = true; 
     } 
    } 

    public boolean isInitialized(){ 
    return initialized; 
    } 

}

然後在測試中使用這樣的:

class TestClass1{ 
    @BeforeClass 
    public void setup(){ 
     TestBootstrap.getInstance().init(); 
    } 


    @Test 
    public void testmethod1(){ 
     // assertions 
    } 

    // .... 

} 

class TestClass2{ 
    @BeforeClass 
    public void setup(){ 
     TestBootstrap.getInstance().init(); 
    } 

    @Test 
    public void testmethod11(){ 
     // assertions 
    } 

    // ... 
} 

通過使用單一實例做了設置爲測試您確保僅執行一次測試環境的初始化,而與測試類的執行順序無關。