Wednesday, October 13, 2010

DataProvider in TestNG


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.
@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.
@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);
 }
In this Implementation we are iterating over the List at the DataProvider level and storing it to another Object[][] result and returning the result.
This implementation will call the test method depending upon the List size.

2.
@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);
  }
 }
In this Implementation we are returning the List itself to the test method and method will iterate over the List data. Both implementation can be used based upon test requirements.

Output of both the implementation shown above remains the same. The only thing that changes is the way you return the data and Iterate.


5 comments :

rahul rana said...
This comment has been removed by a blog administrator.
Boddupally's said...

can we pass the single dp to multiple test methods?

Varun Menon said...

Yes

gayu gayathri said...

can we return a list of list from dp to @test????????????

Varun Menon said...

You can store any object in double object array which is returned by the DataProvidmethod. So you can return the following Object [][List]

Post a Comment