Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing Java tests with data providers

I'm currently doing my first Java project and like to fully TDD it. I'm using JUnit for writing the tests. Apparently JUnit does not provide support for data providers, which makes it rather annoying to test the same method with 20 different versions of an argument. What is the most popular/standard testing tool for Java that does support data providers? I came across TestNG, but have no idea how popular that one is, or how it compares to alternatives.

If there is a way to get this behaviour is a nice way using JUnit, then that might also work.

like image 718
Jeroen De Dauw Avatar asked Oct 05 '13 23:10

Jeroen De Dauw


People also ask

How will you specify a data provider under test annotation?

@DataProvider annotation helps us write data-driven test cases. The @DataProvider annotation enables us to run a test method multiple times by passing different data-sets. The name of this data provider. If it's not supplied, the name of this data provider will automatically be set to the name of the method.

What is data provider in Java?

oracle.olapi.data.source.DataProvider public class DataProvider extends java.lang.Object. Creates user sessions for a connection to Oracle OLAP and creates objects that an application uses in getting metadata objects, in specifying queries, and in retrieving data from a data store.

Does JUnit have data provider?

Apparently JUnit does not provide support for data providers, which makes it rather annoying to test the same method with 20 different versions of an argument.


1 Answers

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.

like image 83
Ingo Bürk Avatar answered Sep 23 '22 11:09

Ingo Bürk