Understanding difference between @Factory and @DataProvider in TestNG
@DataProvider: for a single running instance of script, all methods (which consumes dataprovider) are executed for data provided by DataProvider
@Factory: all methods are executed a TestNG class, in different instances.
eg. DataProvider example:
————————-
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class DataProviderClass {
@BeforeClass
public void beforeClass() {
System.out.println(“@BeforeClass is called”);
}
@Test(dataProvider = “myDP”, dataProviderClass = SimpleTestFactory.class)
public void testMethod(String param) {
System.out.println(“Param from data provider is : ” + param);
}
}
import org.testng.annotations.DataProvider;
public class SimpleTestFactory {
@DataProvider
public Object[][] myDP() {
return new Object[][] { { “Jack” }, { “Joe” } };
}
}
On running DataProviderClass, OUTPUT:
————————————-
@BeforeClass is called
Param from data provider is : Jack
Param from data provider is : Joe
….
===============================================
Default test
Tests run: 2, Failures: 0, Skips: 0
===============================================
@Factory example:
—————–
import org.openqa.selenium.os.Kernel32;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
public class SimpleTest {
private String param = “”;
public SimpleTest(String param) {
this.param = param;
}
@BeforeClass
public void beforeClass() {
System.out.println(“Before SimpleTest class executed.”+Kernel32.INSTANCE.GetCurrentProcessId());
}
@Test
public void testMethod() {
System.out.println(“testMethod parameter value is: ” + param);
}
@Factory
public Object[] factoryMethod() {
return new Object[] { new SimpleTest(“one”), new SimpleTest(“two”) };
}
}
OUTPUT:
———
Before SimpleTest class executed.18216
testMethod parameter value is: two
Before SimpleTest class executed.18216
testMethod parameter value is: one
…
===============================================
Default test
Tests run: 2, Failures: 0, Skips: 0
===============================================
As you can see, with @Factory implementation, beforeClass method is executed before each execution of testMethod. This shows that factory implementation executes the test method for each individual instance of the test class.
0 comments