2012-10-22 38 views

回答

9

不幸的是,你必須編寫這個邏輯。 JUnit沒有這樣的功能。 一般來說,你有2個解決方案:

  1. 只是單獨的測試情況2測試情況:一種是包含需要測試運行「之前」和第二包含不需要此測試。
  2. 實施您自己的測試運行並註釋您的測試使用它。創建您自己的註釋@RequiresBefore並在此註釋中標記需要此項的測試。測試運行器將解析註釋並決定是否運行「before」方法。

第二種解決方案更加清晰。第一個更簡單。這取決於你選擇其中之一。

15

考慮使用@Enclosed跑步者讓你有兩個內部測試類。一個用所需的@Before方法,另一個沒有。

Enclosed

@RunWith(Enclosed.class) 
public class Outter{ 

    public static class Inner1{ 

    @Before public void setup(){} 

    @Test public void test1(){} 
    } 

    public static class Inner2{ 

    // include or not the setup 
    @Before public void setup2(){} 

    @Test public void test2(){} 
    } 

} 
19

您可以用TestRule做到這一點。您標記要與一些描述註釋之前跳過測試,然後,在TestRule的應用方法,您可以測試該批註,做你想做的,是這樣的:

public Statement apply(final Statement base, final Description description) { 
    return new Statement() { 
    @Override 
    public void evaluate() throws Throwable { 
     if (description.getAnnotation(DontRunBefore.class) == null) { 
     // run the before method here 
     } 

     base.evaluate(); 
    } 
    }; 
} 
+0

這裏是更新的鏈接:https://github.com/junit-team/junit/wiki/Rules。另請參閱:http://junit.org/apidocs/org/junit/rules/TestRule.html – Bowen

+4

有沒有方法可以在TestRule中輕鬆執行@Before語句?我想知道'//在這裏運行之前的方法'部分最簡單的方法。 – loeschg

0

也可以通過取消測試案例中設置的@Before所做的操作來解決此問題。 這是怎麼看起來,

@Before 
public void setup() { 
    TestDataSetupClass.setupTestData(); 
} 

@Test 
public void testServiceWithIgnoreCommonSetup() { 
    TestDataSetupClass.unSet(); 
    //Perform Test 
} 

將有解決方案的優點和缺點在這裏。次要的是,這是不必要的設置和取消設置步驟。但是,如果需要僅爲數百個測試用例做好這一點,並避免編寫自我AOP或維護多個內部測試類的開銷,那麼結果就會很好。