2016-12-01 38 views
0

我有一個測試類,使用的理論是這樣的:JUnit的理論套PARAMS爲null

@RunWith(Theories.class) 
public class XTest(){ 
    public static X x1; 
    public static X x2; 
    @DataPoints("xlist") 
    public static X[] xList = {x1, x2}; 
} 

@Before 
public void setUp() throws Exception { 
     x1 = new X(); 
     x2 = new X(); 
} 

@Theory 
public void test(@FromDataPoints("xlist" x){ 
// x is null 
} 

我不明白爲什麼我收到x爲空。我嘗試了與參數化測試相同的操作,但仍爲空。我在這裏錯過了什麼?

+0

_xList_在執行'setUp()'之前創建,所以xList被定義爲'X [] xList = {null,null};'。您可以使用[BeforeClass](http://junit.sourceforge.net/javadoc/org/junit/BeforeClass.html)註釋設置或在靜態範圍內初始化_x1_和_x2_。 –

+0

@matansab你試過我給你的解決方案嗎? – cralfaro

回答

1

代碼中的問題來自「init」命令。

xList是static;因此初始化代碼在您的測試類第一次加載時執行。此時,兩個字段x1和x2仍然在null - 因爲@Before方法將運行以後的

所以,一個簡單的解決這裏可以不使用@Before在所有,但去:

public static X x1 = new X(); 

代替。

0

我想你應該改變你的類的結構,使其工作,因爲我知道理論,這將是正確的結構:

@RunWith(Theories.class) 
public class TheoryTest { 

    @DataPoints("xlist") 
    public static Integer[] xList = new Integer[] {new Integer(1), new Integer(2), new Integer(45)}; 


    @Theory 
    public void singleTest(@FromDataPoints("xlist") Integer x){ 
     // x is null 
     System.out.println("Size " +x); 
    } 
} 

什麼要做的是打電話給你的方法「singleTest」一次爲每個在陣列「的Xlist」的價值觀,因此將值

xList = 1 
xList = 2 
xList = 45 

你不需要申報單變量x1,x2被稱爲3倍。