Data Driven Testing using TestNG


In this tutorial, we will be studying about data driven testing. We will refer to the @DataProvider annotation of TestNG using which we can pass data to the test methods and create a data driven testing framework.

What is Data Driven Testing?

Data driven testing is a test automation technique in which the test data and the test logic are kept separated. The test data drives the testing by getting iteratively loaded to the test script. Hence, instead of having hard-coded input, we have new data each time the script loads the data from the test data source.

Data Driven Testing using @DataProvider

Data driven testing can be carried out through TestNG using its @DataProvider annotation. A method with @DataProvider annotation over it returns a 2D array of object where the rows determines the number of iterations and columns determine the number of input parameters passed to the Test method with each iteration.
This annotation takes only the name of the data provider as its parameter which is used to bind the data provider to the Test method. If no name is provided, the method name of the data provider is taken as the data provider's name.

@DataProvider(name = "nameOfDataProvider")
public Object[][] dataProviderMethodName() {
	//Data generation or fetching logic from any external source	
	//returning 2d array of object

	return new Object[][] {{"k1","r1",1},{"k2","r2",2}};
}

After the creation of data provider method, we can associate a Test method with data provider using 'dataProvider' attribute of @Test annotation. For successful binding of data provider with Test method, the number and data type of parameters of the test method must match the ones returned by the data provider method.

@Test(dataProvider = "nameOfDataProvider")
public void sampleTest(String testData1, String testData2, int testData3) {
	System.out.println(testData1 + " " + testData2 + " " + testData3);
}

Code Snippet for Data Driven Testing in TestNG

@DataProvider(name = "dataProvider1")
public Object[][] dataProviderMethod1() {
	return new Object[][] {{"k1","r1"},{"k2","r2"},{"k3","r3"}};
}

//The test case will run 3 times with different set of values
@Test(dataProvider = "dataProvider1")
public void sampleTest(String str1, String str2) {
	System.out.println(str1 + " " + str2);
}

The above test "sampleTest" will run 3 times with different set of test data - {"k1","r1"},{"k2","r2"},{"k3","r3"} received from 'dataProvider1' dataProvider method.