2015-04-01 84 views
1

我用@Test註解定義了一些類,每個類都有幾個公共方法。所有方法都遵循相同的行爲模式(從ID中檢索資源,如果爲空,則測試日誌,爲資源上的每一行調用真正的測試)。所以,我在一個抽象類,我在每一個方法實例化外在這種行爲,就像這樣:從java運行TestCase並在Eclipse JUnit視圖中顯示結果

@Test 
public void someTest(){ 
    new BasicTestPattern("X","Y","Z"){ // some parameters to retrieve resources 
    @Override 
    protected void testLine(){ 
     someCheck1(); 
     someCheck2(); 
    } 
    }.run(); 
} 

該解決方案消除了每個測試方法10-30線。 現在,我想用一個自定義的註釋走得更遠,這樣的:

@TestPattern(param1="X",param2="Y",param3="Z") 
public void someTest(){ 
    someCheck1(); 
    someCheck2(); 
} 

最後,我創建了一個小框架來以實例化BasicTestPattern並執行所有與這個新的詮釋方法。它在TestCase子類中執行得很好,如下所示:

TestCase junit_test = new TestCase(){ 
    @Override 
    public void runTest() { 
    pattern.run(); 
    } 
}; 

junit_test.run(); 

但是,沒有在Eclipse的JUnit視圖中顯示/列出測試。我只看到測試成功的次數。 我該怎麼做?謝謝。

+0

很好地工作,我發現通過覆蓋現有BlockJUnit4ClassRunner一個潛在的解決方案。 但是,當動態調用測試方法時(從定義主模式的全局方法),即使用反射(m.invoke()),還有另一個問題。當測試方法拋出一個異常(斷言失敗或其他)時,我不能有完整的堆棧跟蹤(它停在方法調用但我看不到裏面)。 有一種方法可以從方法對象獲取堆棧跟蹤,如StackTrace st = m.invoke(...)? – Rififi 2015-04-02 14:37:17

回答

0

您可能需要製作自己的定製Runner才能找到使用@TestPattern方法註釋的所有方法。 (?大概也與@Test

那麼你的測試類看起來就像這樣:

@RunWith(YourRunner.class) 
public class YourTest{ 

    @TestPattern(param1="X",param2="Y",param3="Z") 
    public void someTest(){ 
     ... 
    } 

    @Test 
    public void anotherNormalTest(){ 
     ... 
    } 


} 

This Blog介紹如何編寫自定義的運動員。但是,如果擴展BlockJUnit4ClassRunner以便將特殊的測試方法添加到要運行的測試列表中,您可能就會脫身。

我認爲你只需要重寫computeTestMethods()這個方法,它就是BlockJUnit4ClassRunner如何找到所有要運行的測試方法(用@Test註解的方法),你可以重寫它以找到你用自己的註釋標註的方法。

public class your TestRunner extends BlockJUnit4ClassRunner{ 

    protected List<FrameworkMethod> computeTestMethods() { 
     //this is all the @Test annotated methods 
     List<FrameworkMethod> testAnnotatedMethods = super.computeTestMethods(); 
     //these are all the methods with your @TestPattern annotation 
     List<FrameworkMethod> yourAnnotatedMethods = getTestClass().getAnnotatedMethods(TestPattern.class); 

     //do whatever you need to do to generate the test 
     //methods with the correct parameters based on 
     //the annotation ? 
     //Might need to make fake or 
     //synthetic FrameworkMethod instances? 

     ... 

     //combine everyting into a single List 
     List<FrameworkMethod> allTestMethods =... 
     //finally return all the FrameworkMethods as a single list 
     return allTestMethods; 
} 

} 

您可能必須使自己的FrameworkMethod實現包裝擺脫註釋的信息,做任何設置調用方法之前是必需的。

這將使其與正常的JUnit類無縫集成,並與JUnit的IDE視圖

好運

+0

謝謝!我會盡快嘗試。 – Rififi 2015-04-02 08:12:42