Can I add a junit test case at runtime?
java, junit
Solution
You can use @Parameterized. This will give you what you want. Here is a simple case, to run a test for all files in a single directory:
@RunWith(Parameterized.class)
public class ParameterizedTest {
@Parameters(name = "{index}: file {0}")
public static Iterable<Object[]> data() {
File[] files = new File("/temp").listFiles();
List<Object[]> objects = new ArrayList<Object[]>(files.length);
for (File file : files) {
objects.add(new Object[] { file.getAbsolutePath() });
}
return objects;
}
private final String filename;
public ParameterizedTest(String filename) {
this.filename = filename;
}
@Test
public void test() {
System.out.println("test filename=" + filename);
}
}
Each test in the file is run once for each entry in the list returned by `data()`. You can obviously do what you want with the files, but if you're constructing the list of tests dynamically, then you'll need to have some way of constructing the pass/fail criteria also. So, if you're transforming lots of xml into other xml, then you'll need the resulting xml available as well, maybe in a different directory or with a different (but predictable) name.
Problem
I have a test procedure that need to test lots of `xml` templates. But I found that i have to write a test case for each `xml` template. Does junit have such a mechanism that I can produce another test case inside one test case?