Parameterizing test – DataProvider in TestNg
In this tutorial, we will be discussing about Test parameterization using TestNg. Let say, if you came up with the scenario where you want to test login functionality with multiple credentials, let say 100 or so and you have to login one by one to make sure login is happening with all of these credentials. Here DataDriven approach comes into picture which can be achieved by using DataProvider in TestNg.
Method with DataProvider annotation passes test data to test script. In the below code, we have mentioned just 4 test data sets in DataProvider method. You can increase or decrease test data as per the requirement.
Test script will execute for every test data set.
In below code, @Test Method receives the test data from getData() function which is the DataProvider and you have to mentioned dataProvider name in your test script :
@Test(dataProvider = "getData")
Complete Code
import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DataProviderSampleTest { // getdata function passes the test data to test script @Test(dataProvider = "getData") public void loginTest(String username, String password) { System.out.println("UserName : " + username); System.out.println("Password : " + password); //Selenium code } @DataProvider public Object[][] getData() { // Rows - Test repetition depends on number of rows. // Columns - Number of parameters in test script. // Number of columns should be same as the number of input parameters in Test script Object[][] data = new Object[4][2]; // 1st row data[0][0] = "testuser1"; data[0][1] = "pass"; // 2nd row data[1][0] = "testuser2"; data[1][1] = "pass2121"; // 3rd row data[2][0] = "testuser3"; data[2][1] = "wswkdsj"; // 4th row data[3][0] = "testuser4"; data[3][1] = "skaalk"; return data; } }
When you execute the above test script, it will iterate four times(every time with different sets of data) as we have mentioned 4 test data sets in DataProvider method. So basically, test script iteration depends on number of test data sets mentioned in DataProvider method.
OutPut of above Program will be