There are many times different TestNG data provider required in a Selenium script, sometimes the same set of data & sometimes different sets of data. There is a way to use a same TestNG data provider with different sets of data and by doing this we can prevent redundant code.
Let's say we need data provider for "LoginTest" and "RegistrationTest" and both would require different sets of data. To do so we can use below code to use same data provider with different sets of data.
@DataProvider(name="sampleDataProvider")
//When sampleDataProvider is called in any test method, Method m will automatically pass a name of that method as a reference value
public static Object[][] abcData(Method m){
Object data [][]=null;
//Data for LoginTest
if(m.getName().equals("LoginTest")){
data=new Object[1][2]
data=new Object[1][2]
data[0][0]="Username1";
data[0][1]="Password1";
}
//Data for RegistrationTest
else if (m.getName().equals("RegistrationTest")){
data=new Object[2][3];
data=new Object[2][3];
data[0][0]="emailAddress1";
data[0][1]="Username1";
data[0][2]="Password1";
data[1][0]="emailAddress2";
data[1][1]="Username2";
data[1][2]="Password2";
}
return data;
}
Using above code we can create a single data provider for all the Selenium scripts.