Junit Parameterized tests allow a developer to run the same test multiple times with different parameter values.
This is very useful feature that greatly improves quality of testing.
In order to use parameterized tests you need to annotate test class with @RunWith(Parameterized.class).
Then you create a public static method that returns a Collection of Objects – this will be your test data set.
Annotate this method with @Parameters. The code example below has method called data(), we give it a meta-name “FileSet” and specify that there are two of the parameters:
- inputCsvFile {0}
- and xmlFile {1}
The sample method data() returns two rows, each row containing {0} and {1} parameters.
The test case will be invoked once for each row of data.
package test; import static org.junit.Assert.*; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.Collection; import org.junit.runners.Parameterized; import org.xmlunit.builder.Input; import org.xmlunit.diff.ComparisonResult; import org.xmlunit.diff.DifferenceEvaluator; import org.xmlunit.matchers.CompareMatcher; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Parameterized.class) public class TestParser { @Parameterized.Parameter(value = 0) public String inputCsvFile; @Parameterized.Parameter(value = 1) public String xmlFile; @Parameterized.Parameters(name = "FileSet: {0},{1}") public static Collection < String[] > data() { return Arrays.asList(new String[][] { { "test-01.csv", "test-01-output.xml" }, { "test-01.csv", "test-01-output.xml" } }); } @Test public void testParser() throws IOException { String fileSetLocation = "src/test/resources/test-parser/"; String csv = new String(Files.readAllBytes(Paths.get(fileSetLocation + inputCsvFile))); String expectedXmlOut = new String(Files.readAllBytes(Paths.get(fileSetLocation + xmlFile))); String xmlProduced = Parser.parse(csv); assertTodaysMatch(xmlProduced, expectedXmlOut); } public static void assertTodaysMatch(String xml, String expectedOut) { assertThat(xml, CompareMatcher.isSimilarTo(Input.fromString(expectedOut)) .withDifferenceEvaluator(assertTodayDateForXpathContaining("today")) .normalizeWhitespace() .ignoreComments() .throwComparisonFailure()); } public static DifferenceEvaluator assertTodayDateForXpathContaining(String...tags) { return (comparison, outcome) - > { if (ComparisonResult.EQUAL == outcome) { return outcome; } else if (Arrays.asList(tags).stream().anyMatch(tag - > comparison.getTestDetails().getParentXPath().contains(tag))) { String today = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE); return today.equals(comparison.getTestDetails().getValue()) ? ComparisonResult.EQUAL : outcome; } else { return outcome; } }; } }