Writing Java tests with data providers
Depending on your needs in flexibility vs readability, you can choose Parameterized
- junit's built in option, described by dkatzel. Other options are external junit runners provided by external libraries like zohhak, which let's you do:
@TestWith({
"clerk, 45'000 USD, GOLD",
"supervisor, 60'000 GBP, PLATINUM"
})
public void canAcceptDebit(Employee employee, Money money, ClientType clientType) {
assertTrue( employee.canAcceptDebit(money, clientType) );
}
or junitParams with a bit different functionality. just pick whatever suits you the most
JUnit 4 has parameterized test which is the does the same thing as php data providers
@RunWith(Parameterized.class)
public class MyTest{
@Parameters
public static Collection<Object[]> data() {
/*create and return a Collection
of Objects arrays here.
Each element in each array is
a parameter to your constructor.
*/
}
private int a,b,c;
public MyTest(int a, int b, int c) {
this.a= a;
this.b = b;
this.c = c;
}
@Test
public void test() {
//do your test with a,b
}
@Test
public void testC(){
//you can have multiple tests
//which all will run
//...test c
}
}
Coworkers of mine at our company wrote a freely available DataProvider in TestNG style for JUnit which you can find on github (https://github.com/TNG/junit-dataprovider).
We use it in very large projects and it works just fine for us. It has some advantages over JUnit's Parameterized
as it will reduce the overhead of separate classes and you can execute single tests as well.
An example looks something like this
@DataProvider
public static Object[][] provideStringAndExpectedLength() {
return new Object[][] {
{ "Hello World", 11 },
{ "Foo", 3 }
};
}
@Test
@UseDataProvider( "provideStringAndExpectedLength" )
public void testCalculateLength( String input, int expectedLength ) {
assertThat( calculateLength( input ) ).isEqualTo( expectedLength );
}
Edit: Since v1.7, it also supports other ways to provide data (strings, lists) and can inline the provider so that a separate method is not necessarily needed.
A full, working example can be found on the manual page on github. It also has a few more features, like collecting the providers in utility classes and accessing them from other classes etc. The manual page is very detailed, I'm sure you'll find any questions answered there.