We are going to show how to use the DataProvider in your test cases created with the TestNG unit testing framework.
DataProvider are used in order to create data-driven tests. Basically, it will help you to run the same test case, but with different data sets.

Examples of DataProviders

We are going to use the two dimensional object array Object[][] in order to return data and make use of it in the test case.

In order to create a DataProvider, you need to:
– create a new method with the two dimensional object array Object[][] as a return type
– add the DataProvider annotation to the method
– give a name for the DataProvider
– return a new two dimensional object array Object[][] with the desired values for the test

Here are some examples of values that can be provided for the DataProvider in TestNG:


@DataProvider(name = "provideDaysInterval")
public Object[][] provideData() {
return new Object[][]{{1}, {2}, {28}, {110}, {365}, {400}, {800}};
}


@DataProvider(name = "invalidIds")
public Object[][] provideInvalidIds() {
return new Object[][]{{"a"}, {"asdasdasf"}, {"£!@$%^&*^(&*&^%£$@£!"}, {"1"}, {"2332423"}, {"123456786543sadfgh"}, {"1234567890"}};
}

@DataProvider(name = "minMaxDates")
public Object[][] provideMinMaxDateRanges() {
return new Object[][]{
{"2013-01-04", "2014-01-04", "2014-04-04", "2015-07-04"},
{"2013-01-04", "2013-04-04", "2014-04-04", "2014-07-04"}
};
}

Now, you can make use of these DataProviders in your test cases by following the below steps:

– add the dataProvider attribute to the @Test annotation, and specify which is the dataProvider that you want to use. Make sure the data types defined in the two dimensional object array Object[][] are reflected in your test method attributes, see more details about the implementation of the DataProvider in TestNG:


@Test(groups = {"smoke"}, dataProvider = "provideDaysInterval")
public void test_Days_Are_Valid(int numberOfDaysInterval){


}

@Test(groups = {"smoke"}, dataProvider = "minMaxDates")
public void test_Data_Ranges_Validate_Min_Max(String startDateFirst, String endDateFirst, String startDateLast, String endDateLast){

}

This is the way to created automated data-driven test cases with TestNG and DataProviders in Java.

 

We found the use of DataProviders very useful, especially for API Testing and UI Testing with Selenium WebDriver. More details on how to find web elements in Selenium WebDriver can be found here.

 

Click here for Online Tutorial for using Java and TestNG for testing with Selenium WebDriver.

How fast is your website? Free Website Speed Test