Letâs learn about the @Factory annotation provided by TestNG. @Factory allows tests to be created at runtime depending on certain data-sets or conditions
The @Factory annotation will help you create tests to be created at runtime based on certain data-set or conditions.
Often times you may have to execute tests with different values. To do that, you might have to define separate set of tests inside a suite.xml file. This is not scalable solution as if you get an extra data or different set of data, you will have to redefine the whole set of tests.
Using @Factory you can create dynamic tests at run time.
Eg.
public class ExampleTest
{
@Test
public void myTest() {
System.out.println("My test");
}
}
public class ExampleTestFactory
{
@Factory
public Object[] factoryMethod() {
return new Object[] { new SimpleTest(), new SimpleTest() };
}
}
So in above example, tests will be executed twice. It is mandatory that factory method should return an array of Object.
Example with passing parameters.
Eg.
public class ExampleTest
{
private String browser;
public ExampleTest(String browser) {
this.browser = browser;
}
@Test
public void testMethodOne() {
System.out.println("Selected browser is: " + browser);
}
}
public class SimpleTestFactory
{
@Factory
public Object[] factoryMethod() {
return new Object[] { new ExampleTest("firefox"), new ExampleTest("chrome") };
}
}
Hope that clears your doubt.