dataprovider code example
Example 1: what is dataprovider in testng
DataProvider returns a single or multi-dimensional JAVA Object
array to the test method and the test method will invoke x times
in a (x multiply n) type of object array. For example, if the DataProvider
returns an array of 3*2 objects, the corresponding test case will be
invoked 3 times with 2 parameters each time.
@Test(dataProvider="myData")
public void testMethod(String author,String searchKey) throws InterruptedException{
{
//CODES HERE
}
@DataProvider(name="myData")
public Object[][] getDataFromDataprovider(){
Object[][] obj = {{ "Guru99", "India" }, { "Krishna", "UK" },
{ "Bhupesh", "USA" }};
return obj;
}
Example 2: dataprovider vs factory
@DataProvider – DataProvider returns a single or multi-dimensional JAVA Object
array to the test method and the test method will invoke x times
in a (x multiply n) type of object array. For example, if the DataProvider
returns an array of 3*2 objects, the corresponding test case will be
invoked 3 times with 2 parameters each time.
@Factory – annotation is useful when we want to run multiple test
cases through a single test class. It is mainly used for the dynamic
execution of test cases.
Let's say we have in 2 different classes, there are 2 different test cases.
If we want to run both in the same class. We use @Factory annotaions which
takes Object[] array. We put the test cases into it. it returns Object array
value.
Example 3: how do you use data provider
DataProvider returns a single or
multi-dimensional JAVA Object array
to the test method and the test method,
will invoke M times in a M*N type of object array.
For example, if the DataProvider returns
an array of 3*2 objects, the corresponding
test case will be invoked 3 times with 2 parameters each time.
@Test(dataProvider="myData")
public void testMethod(String author,String searchKey){
{
//CODES HERE
}
@DataProvider(name="myData")
public Object[][] getDataFromDataprovider(){
Object[][] obj={{ "Guru99", "India" }, { "Krishna", "UK" },{ "Bhupesh", "USA" }};
return obj;
}