DataProvider in TestNG
TestNG supports two different ways of passing parameter values.
1. Parametrization through .xml file
2. DataProvider
- Parametrization through .xml file is one of the methods of passing parameter values. This method is useful if the data set is limited to just a few rows.
- To provide data from DataProvider we need to declare a method that returns the data set in the form of two dimensional object array Object[][].
- The first array represents a data set whereas the second array contains the parameter values.
- The DataProvider method can be in the same test class or one of its super classes.
- It is also possible to provide DataProvider in another class but then the method has to be static.
Calling DataProvider from Same Class
package qa_simple_data_provider;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class Simple_Data_Provider {
@Test(dataProvider = "ProvideData")
public void getData(int age, String name){
System.out.println("Running DataProvider from Same class");
System.out.println("Mr "+ name + " your age is "+ age);
}
@DataProvider
public Object[][] ProvideData(){
return new Object[][]{{24,"Adam"},{23,"Erwin"}};
}
}
Calling DataProvider from Other Class
//DataProvider Class
package qa1;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class Simple_Data_Provider {
@DataProvider
public static Object[][] ProvideData(){
return new Object[][]{{24,"Adam"},{23,"Erwin"}};
}
}
// Method which will use DataProvider
package qa;
import org.testng.annotations.Test;
public class Get_Data_From_Other_Class {
@Test(dataProvider = "ProvideData", dataProviderClass=qa1.Simple_Data_Provider.class)
public void getData(int age, String name){
System.out.println("Running Data Provider from other class");
System.out.println("Mr "+ name + " your age is "+ age+ " on 02-Aug-2015");
}
}
Sample Testng.xml file
<?xml version="1.0" encoding="UTF-8"?>
<suite name="StaticDataProviderExampleSuite" parallel="false">
<test name="StaticDataProviderTest">
<classes>
<class name="qa.Get_Data_From_Other_Class"/>
</classes>
</test>
</suite>
While accessing the DataProvider method from other class we will make only 2 changes.
1. The DataProvider method should be declared as static.
2. The method in other class which will use the DataProvider class should specify both DataProvider name and its class in the @Test attributes.