2015-10-15 23 views
1

我正在考慮將預期數據發送到構造函數,但後來意識到這是一個愚蠢的想法。JUnit數據驗證 - 將多組「預期」數據發送到測試中

我仍然寧願最小化打字。


我有一個廣泛的XML配置文件。它內部的一些元素可能會出現多次(例如,多個channel標籤)。對於這些元素,我的計劃是製作一個「測試器」,可以調用它來驗證每個單獨的通道各自的值。我不知道如何用JUnit來做到這一點。

該計劃是有2配置文件與相反的配置。


參數化是答案。謝謝。

這是我掀起了一個例子,如果有人想進一步的例子:要使用多個參數進行測試案例

@RunWith(Parameterized.class) 
public class GlobalTester{ 
    @Parameter(0) 
    public Configuration config; 
    @Parameter(1) 
    public boolean debug; 

    @Parameters 
    public static Collection<Object[]> params() throws Exception{ 
     List<Object[]> inputs = new LinkedList<Object[]>(); 

     Object[] o = new Object[2]; 
     o[0] = ConfigurationSuite.load(1); 
     o[1] = true; 
     inputs.add(o); 

     o = new Object[2]; 
     o[0] = ConfigurationSuite.load(2); 
     o[1] = false; 
     inputs.add(o); 

     return inputs; 
    } 

    @Test 
    public void debug(){ 
     assertEquals(debug, config.getGeneral().isDebug()); 
    } 
} 
+0

沒有考慮過'@ Parameterized'? – Makoto

回答

1

一種方法是使用JUnit提供的Parameterized API。

下面是在同一測試用例中使用它讀取不同XML文件的一個示例。

import java.nio.file.Files; 
import java.nio.file.Paths; 
import java.util.ArrayList; 
import java.util.Collection; 

import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.junit.runners.Parameterized; 
import org.junit.runners.Parameterized.Parameters; 

@RunWith(Parameterized.class) 
public class ConfigTest { 

    private String xmlFile; 

    public ConfigTest(String xmlFile) { 
     this.xmlFile= xmlFile; 
    } 

    @Test 
    public void testXml() throws Exception { 
     System.out.println(xmlFile); 
    } 

    @Parameters 
    public static Collection<String> data() throws Exception{ 
     String file1 = new String(Files.readAllBytes(Paths.get(ConfigTest.class.getResource("config1.xml").toURI()))); 
     String file2 = new String(Files.readAllBytes(Paths.get(ConfigTest.class.getResource("config2.xml").toURI()))); 

     Collection<String> data = new ArrayList<String>(); 
     data.add(file1); 
     data.add(file2); 
     return data; 

    } 

}