There are many functions provided by TestNG and you can use them in different ways one of them I will mention in this blog.
@DataProvider
A DataProvider provide data to the function which depends on it. And whenever we define a DataProvider it should always return a double object array “Object[][]”. The function which calls dataprovider will be executed based on no. of array returned from the DataProvider. For ex.
1
2
3
4
5
6
7
8
9
| @Test(dataProvider= "data" ) public void printMethod(String s){ System.out.println(s); } @DataProvider(name= "data" ) public Object[][] dataProviderTest(){ return new Object[][]{{ "Test Data 1" },{ "Test Data 2" },{ "Test Data 3" }}; } |
The Output will be:
Test Data 1
Test Data 2
Test Data 3
As you can see that the Test method “printMethod ” gets called 3 times depending upon the data that was provided by the DataProvider.The DataProvider can be used for getting data from some file or database according to test requirements.Following I will mention two ways to use DataProvider:For ex.You need to get data from a file and print each line to the console. For doing that you had written some File Processing API that will return a List of the data read from file.You can iterate on the List at the DataProvider level as well as at the test method level. Both I am mentioning below.
1.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@DataProvider(name =
"data"
)
public Object[][] init1() {
List list = fileObject.getData();
Object[][] result=
new
Object[list.size()][];
int i=0;
for
(String s:list){
result[i]=
new
Object[]{
new
String(s)};
i++;
}
return
result;
}
@Test(dataProvider=
"data"
)
public void runTest1(String s){
System.out.println(
"Data "
+s);
}
2.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| @DataProvider(name = "data" ) public Object[][] init() { List list = fileObject.getData(); return new Object[][]{{list}}; } @Test(dataProvider= "data" ) public void runTest(List list){ for (String s:list){ System.out.println(“Data” + s); } } |
Output of both the implementation shown above remains the same. The only thing that changes is the way you return the data and Iterate.