In our previous post we figured out how to use DataProviders in JUnit tests - for some reason JUnit doesn’t support that from the box.

Fortunately there is com.tngtech.java:junit-dataprovider

Unfortunately attempts to use that in Spring driven tests will fail. It doesn’t work with Spring.

SpringDataProviderRunner

Spent some time on searching on the internet for possible solutions and found there is only one option - we need a different test runner. Yay! - a workaround for a workaround.

Note: The code below is the solution that I found on the internet and copied-pasted without any change. Don’t know who the author is - if you know the author let me know, I can add the link/reference here.

JUnit DataProvider with Spring example

The complete work JUnit DataProvider with Spring example that uses our custom SpringDataProviderRunner

JUnit DataProviders Maven dependency

<dependency>
    <groupId>com.tngtech.java</groupId>
    <artifactId>junit-dataprovider</artifactId>
    <version>1.13.1</version>
    <scope>test</scope>
</dependency>
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;

@RunWith(SpringDataProviderRunner.class)
@SpringBootTest(classes = TestsContext.class)
public class JUnitDataProviderWithSpringExampleIT {

    @DataProvider
    public static Object[][] sumTestData() {
        return new Object[][]{
                {2, 2, 4},
                {10, 1, 11},
                {1000000, -1000000, 0}
        };
    }

    @Test
    @UseDataProvider("sumTestData")
    public void dataProviderTest(int a, int b, int expectedSum) {
        Assert.assertEquals(expectedSum, a + b);
    }

}

Yes, doesn’t look very elegant but… this is America JUnit


You may also find these posts interesting: