Quicktip! TestNG’s-like junit-dataprovider Instead of JUnit Parameterized Class

We all know JUnit test-classes can be parameterized, which means that for a given set of test-elements the test class is instantiated a few times, but using constructors for that isn’t always what you want.

I’ve taken the StringSortTest from this blog as an example.

@RunWith(Parameterized.class)
public class StringSortTest {

    @Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] {
                         { "abc", "abc" },
                         { "cba", "abc" },
         });
    }

    private final String input;
    private final String expected;

    public StringSortTest(final String input, final String expected) {
        this.input = input;
        this.expected = expected;
    }

    @Test
    public void testSort() {
        assertEquals(expected, mySortMethod(input));
    }
}

This is pretty darn obnoxious some times if you have multiple sets of data for various tests, which all go through the constructor which would force you to write multiple test classes. TestNG solves this better by allowing to provide separate data sets to individual test methods using the @DataProvider annotation. Continue reading “Quicktip! TestNG’s-like junit-dataprovider Instead of JUnit Parameterized Class”