DataProvider in TestNG | Data Driven Testing
In TestNG, the @DataProvider annotation is used to provide a way to supply multiple sets of data to a single test method. This is useful when you want to run the same test method with different data inputs.
@DataProvider
- You can define a method that returns an array of data, which will be fed into a test method.
- The @DataProvider method can return either a two-dimensional array of Object, Iterator< Object[ ]>, or Object [ ][ ].
- Each row of data will be passed as parameters to the test method during execution.
Syntax
- Define a method with @DataProvider that returns the test data.
- Use the dataProvider attribute in the @Test annotation to link the test method to the data provider.
Test Code
package asc;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class DataProviderTest {
@Test(dataProvider="dataset")
public void test(String username, String password) {
System.out.println(username+"============"+password);
}
@Test(dataProvider="dataset1")
public void test1(String username, String password, String test)
{
System.out.println(username+"===="+password+"===="+test);
}
@DataProvider
public Object[][] dataset1(){
return new Object[][] {
{"username","password","test"},
{"username1","password1","test1"},
{"username2","password2","test2"},
{"username3","password3","test3"}
};
}
@DataProvider
public Object[][] dataset() {
Object[][] dataset = new Object[4][2];
//first row
dataset[0][0]="user1";
dataset[0][1]="pass1";
//second row
dataset[1][0]="user2";
dataset[1][1]="pass2";
//third row
dataset[2][0]="user3";
dataset[2][1]="pass3";
//fourth row
dataset[3][0]="user4";
dataset[3][1]="pass4";
return dataset;
}
}
Run this Code