Oliver Wehrens
Seasoned Technology Leader. Mentor. Dad.
Oliver Wehrens

Using TestNG with DataProviders to cover more test cases

- 2 min

A couple of days ago I had the case that I needed to test a method with different parameters. I ended up writing a couple of test methods differing only in passing various arguments to the unit under test.

Tonight I was at a TestNG talk and while I knew most of the stuff already the DataProviders (which I heard of before but unfortunately never really payed attention to) really caught me.

Now I can create a** DataProvider which generates test data**. Each of these data sets will result in call of the test method with the corresponding arguments.

The following code will test a String to Property Converter if it works correctly. It takes two parameters, first the string to be converted, second the result which I will assert.

@Test(dataProvider = "convertTestDataProvider")
public void testConvert(String property, String result)
{
    Properties properties =
      stringPropertyConverter.convertString(property);
    Assert.assertTrue(properties.get("A").equals(result));
  }

Now the DataProvider must return an array of array of objects. TestNG will cast the return values to the method signature of all the tests with the corresponding annotation.

    @DataProvider(name = "convertTestDataProvider")
    public Object[][] convertTestDataProvider()
    {
        return new Object[][]{
                {"A=", ""},
                {"A=1", "1"},
                {"A=2=3", "2=3"},
                {"A=2" + StringPropertyConverter.ideaLineSeperator +
                 "# Comment" +
                 StringPropertyConverter.ideaLineSeperator + "C=1", "2"},
        };
    }

Here I cover 4 test cases. It is very easy to add more tests just by adding one more line with the values to test and the expected result. TestNG results with DataProvider This will save me some amount of time.

Good Job Cedrik & friends.

Next step: How to make sure you cover all the relevant test cases (and having a systematic way of getting there). Anybody has an Idea?