Difference between @Data Provider and @Factory Method


DataProvider: A test method that uses DataProvider will be executed a multiple number of times based on the data provided by the DataProvider. The test method will be executed using the same instance of the test class to which the test method belongs.

Factory: A factory will execute all the test methods present inside a test class using a separate instance of the respective class.(means create instances of test classes dynamically)


Let see difference with example


Example @DataProvider

package testngexp;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

publicclassdpdifffactory {
@BeforeClass
publicvoid beforemethod(){
System.out.println("Before Method executed");
}

@Test(dataProvider="dpdifffact")
publicvoid TestMethod1(String msg){
System.out.println("This is "+msg);
}

@Test(dataProvider="dpdifffact")
publicvoid TestMethod2(String msg){
System.out.println("This is "+msg);
}

@DataProvider(name="dpdifffact")
public Object[][] getdata(){
returnnew Object[][]{
{"Test Method1"},{"TestMethod2"}};
}
}

TestNG.xml

<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEsuiteSYSTEM"http://testng.org/testng-1.0.dtd">
<suitename="Suite"verbose="1">
<testname="Test1">
<groups>
<run>
<excludename="A"/>
</run>
</groups>
<classes>
<classname="testngexp.dpdifffactory"/>
</classes>
</test><!-- Test -->
</suite><!-- Suite -->

Results
image

Here, Before Method is Executed only one time


Example2 @Factory


package testngexp;
import org.testng.annotations.BeforeClass;
importorg.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;

publicclass dpdifffactory {
String msg;
public dpdifffactory(String msgstr){
msg=msgstr;
}

@BeforeClass
publicvoid beforemethod(){
System.out.println("Before Method executed");
}

@Test
publicvoid TestMethod1(){
System.out.println("This is "+msg);
}

@Factory
public Object[] getdata(){
Object[] res=new Object[2];
res[0]=new dpdifffactory("TestMethod1");
res[1]=new dpdifffactory("TestMethod2");
return res;
}
}

TestNG.xml

<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEsuiteSYSTEM"http://testng.org/testng-1.0.dtd">
<suitename="Suite"verbose="1">
<testname="Test1">
<groups>
<run>
<excludename="A"/>
</run>
</groups>
<classes>
<classname="testngexp.dpdifffactory"/>
</classes>
</test><!-- Test -->
</suite><!-- Suite -->

Results
image

Here, before Method executed twice (mean before class method is executed before each execution of the TestMethod1

Comments