Reputation: 864
I was thinking of sending the expected data into a constructor but then realized it was a silly idea.
I still would rather minimize typing.
I have an extensive xml config file. Some elements inside of it may appear multiple times (ei, multiple channel
tags). For those elements my plan was to make a 'tester' that can be called to validate each individual channel & their respective values. I'm at a loss of how to do this with JUnit.
The plan is to have 2 config files with opposing configurations.
Parameterized was the answer. Thanks.
Here's an example I whipped up if anyone wants further examples:
@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());
}
}
Upvotes: 1
Views: 863
Reputation: 1
This is one good solution to use Parameterized but with this there will be one problem, If we want to have other test cases that we should run as individual test without Parameterized then that we can't do.
To resolve that issue we can use @Suite.SuiteClasses or @Enclosed
Or other way we can use simple option @Theories and @DataPoint , which will be a simple solution to the above problem.
Upvotes: 0
Reputation: 15094
One way to use multiple parameters for test cases is to use the Parameterized API provided by JUnit.
Here is one example reading different XML files while using it in the same test case.
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;
}
}
Upvotes: 1