2014-03-13 250 views
4

我正在使用JUnit測試套件來運行一些測試,其中一個測試使用@Parameterized運行多次。我發現當我運行我的測試時,@Parameterized函數在@BeforeClass之前運行。這是預期的行爲還是其他事情發生?我希望@BeforeClass能在任何測試開始之前運行。JUnit @Parameterized函數在測試套件中的@BeforeClass之前運行?

這裏是我的測試套件:

@RunWith(Suite.class) 
@SuiteClasses({ Test1.class, Test2.class }) 
public class TestSuite { 

    @BeforeClass 
    public static void setup() throws Exception { 
     // setup, I want this to be run before anything else 
    } 

} 

Test1的使用@Parameterized:

public class Test1 { 

    private String value; 

    // @Parameterized function which appears to run before @BeforeClass setup() 
    @Parameterized.Parameters 
    public static Collection<Object[]> configurations() throws InterruptedException { 

     // Code which relies on setup() to be run first 

    } 

    public Test1(String value) { 
     this.value = value; 
    } 

    @Test 
    public void testA() { 
     // Test 
    } 
} 

我怎樣才能解決這個運行@BeforeClass設置()函數運行先天下之憂?

回答

6

不幸的是,這是按預期工作的。 JUnit需要在開始測試之前列舉所有測試用例,並且對於參數化測試,用@Parameterized.Parameters註解的方法用於確定有多少測試。

+0

好感謝,你對如何實現我需要的功能,有什麼建議? –

+0

@CoreyWu你能告訴我們你想要解決什麼問題嗎? – NamshubWriter

+0

我也有這個問題。在設置我的測試之前,我正在嘗試做數據庫準備。 My @Parameters方法查詢數據庫以查找測試值。我想在獲取測試值之前設置數據庫。 不,這不是嚴格的單元測試.... – bobanahalf

4

雖然有點different的解決方案,但是一個靜態塊可以解決這個問題。還要注意,它必須在Test1.class中。但旁邊的它的作品;-)

@RunWith(Parameterized.class) 
public class Test1 { 

    static{ 
     System.out.println("Executed before everything"); 
    } 

    private String value; 

    // @Parameterized function which appears to run before @BeforeClass setup() 
    @Parameterized.Parameters 
    public static Collection<Object[]> configurations() throws InterruptedException { 
     // Code which relies on setup() to be run first 
    } 

    public Test1(String value) { 
     this.value = value; 
    } 

    @Test 
    public void testA() { 
     // Test 
    } 
} 
2

最近碰到類似的問題,並使用函數解決了問題。下面的例子。

@RunWith(Parameterized.class) 
public class MyClassTest { 

    @Parameterized.Parameters 
    public static Iterable functions() { 
     return Arrays.<Object, Object>asList(
      param -> new Object() 
     ); 
    } 

    Object param; 
    Function function; 

    public MyClassTest(Function f) { 
     this.function = f; 
    } 

    @Before 
    public void before() { 
     // construct dependency 
     param = "some value"; 
    } 

    @Test 
    public void test() { 
     assertThat(myClass.doSomething(function.apply(param)), is(equalTo(expectedValue))); 
    } 
} 

在你的情況下,做數據庫安裝在@Before或@BeforeClass然後注入功能

相關問題