在執行每個測試之前,我的測試類中的所有測試都執行'before'方法(用JUnit的@Before
註釋)。從JUnit中的'before'方法中排除個別測試
我需要一個特定的測試不執行此方法之前。
有沒有辦法做到這一點?
在執行每個測試之前,我的測試類中的所有測試都執行'before'方法(用JUnit的@Before
註釋)。從JUnit中的'before'方法中排除個別測試
我需要一個特定的測試不執行此方法之前。
有沒有辦法做到這一點?
不幸的是,你必須編寫這個邏輯。 JUnit沒有這樣的功能。 一般來說,你有2個解決方案:
@RequiresBefore
並在此註釋中標記需要此項的測試。測試運行器將解析註釋並決定是否運行「before」方法。第二種解決方案更加清晰。第一個更簡單。這取決於你選擇其中之一。
考慮使用@Enclosed
跑步者讓你有兩個內部測試類。一個用所需的@Before
方法,另一個沒有。
@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(){}
}
}
您可以用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();
}
};
}
也可以通過取消測試案例中設置的@Before
所做的操作來解決此問題。 這是怎麼看起來,
@Before
public void setup() {
TestDataSetupClass.setupTestData();
}
@Test
public void testServiceWithIgnoreCommonSetup() {
TestDataSetupClass.unSet();
//Perform Test
}
將有解決方案的優點和缺點在這裏。次要的是,這是不必要的設置和取消設置步驟。但是,如果需要僅爲數百個測試用例做好這一點,並避免編寫自我AOP或維護多個內部測試類的開銷,那麼結果就會很好。
這裏是更新的鏈接:https://github.com/junit-team/junit/wiki/Rules。另請參閱:http://junit.org/apidocs/org/junit/rules/TestRule.html – Bowen
有沒有方法可以在TestRule中輕鬆執行@Before語句?我想知道'//在這裏運行之前的方法'部分最簡單的方法。 – loeschg