Liked TestNG DataProviders but have to use JUnit?
This is an example how to use TestNG like DataProviders in JUnit.
JUnit DataProviders Maven dependency
<dependency>
<groupId>com.tngtech.java</groupId>
<artifactId>junit-dataprovider</artifactId>
<version>1.13.1</version>
<scope>test</scope>
</dependency>
DataProvider in JUnit tests
First of all you need to annotate your test class with @RunWith(DataProviderRunner.class)
Then create DataProvider
@DataProvider
public static Object[][] sumTestData() {
return new Object[][]{
{2, 2, 4},
{10, 1, 11},
{1000000, -1000000, 0}
};
}
To use that data provider you should annotate you test with @UseDataProvider("sumTestData")
.
JUnit DataProvider example
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(DataProviderRunner.class)
public class JUnitDataProviderExampleIT {
@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);
}
}
It’s working…
… but why doesn’t JUnit support it from the box?
Want to use DataProviders with JUnit and Spring? This is another pain…
You may also find these posts interesting: