Over a million developers have joined DZone.

Alternative to JUnit Parameterized Classes: junit-dataprovider

DZone 's Guide to

Alternative to JUnit Parameterized Classes: junit-dataprovider

· Java Zone ·
Free Resource

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.

public class StringSortTest {

    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;

    public void testSort() {
        assertEquals(expected, mySortMethod(input));
This is pretty darn obnoxious sometimes 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 you to provide separate data sets to individual test methods using the @DataProvider annotation.

But don’t worry, now you can achieve the same with the junit-dataprovider, available on Github. Pull in the dependency with e.g. Maven.

The above example now could be rewritten as:
public class StringSortTest {

    public static Object[][] data() {
        return new Object[][] {
                         { "abc", "abc" },
                         { "cba", "abc" },

    public void testSort(final String input, final String expected) {
       assertEquals(expected, mySortMethod(input));
You’ll see: no constructor. In this example it doesn’t have many benefits, except maybe for less boiler-plate, but now you can create as many @DataProvider-annotated methods which are fed directly to your @UseDataProvider-annotated testmethod(s).

Sidenote for Eclipse: If you’re using that IDE, the JUnit plugin is unable to map the names of the passed/failed testmethods to the ones in the testclass correctly. If a method fails, you’ll have to find it back manually in the testclass (or vote for the patch Andreas Smidt created to get this fixed in Eclipse).


In the mean time, if you’re stuck with JUnit and you’d love to use this feature you’re so accustomed to using with TestNG, go ahead and try the junit-dataprovider now.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}