Is it possible to add a junit test case at runtime?

I have a testing procedure that should validate a lot of xml templates.

But I found that I need to write a test case for each xml template.

Does junit have such a mechanism that I can create another test case in one test case?

+4
source share
2 answers

You can use @Parameterized . This will give you what you want. Here is a simple example: run a test for all files in one 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 dynamically create a list of tests, you will also need to somehow build the criteria for passing / failing. So, if you convert a lot of xml to another xml, then you will also need the resulting xml, perhaps in a different directory or with a different (but predictable) name.

+4
source

No, there is no functionality like โ€œtest case inside test caseโ€, except for loops!

Cycles to the rescue!

 @Test public void xmlShouldBeValid() { String[] templates = new String[]{ TEMPLATE1, TEMPLATE2, TEMPLATE3 }; for (String template : templates) { testTemplate(template); } } private void testTemplate(String template) { assertEquals("whatever", template); } 

Something like this might help. Another trick I use is to make helper methods assert *. So if I check that XML has 3 attributes a, b and c, I can write

 private void assertTemplate(String template, String a, String b, int c) { String aFromTemplate = parseAfromTemplate(template); // normally this is done inline String bFromTemplate = parseBfromTemplate(template); // but a function to read easier String cFromTemplate = parseCfromTemplate(template); assertEquals(a, aFromTemplate); assertEquals(b, bFromTemplate); assertEquals(c, cFromTemplate); } 

Now you can call assertTemplate several times in one test function:

 @Test public void xmlShouldBeValid() { assertTemplate("<hardcoded xml object>", "a", "b", "c"); assertTemplate("<hardcoded xml object>", "r", "s", "t"); assertTemplate("<hardcoded xml object>", "x", "y", "z"); } 

Of course, instead of using String for the template type, replace the XML object with any framework (if any) that you are using.

0
source

All Articles