Checkout our demo site to practice selenium https://magento.softwaretestingboard.com/

0 like 0 dislike
361 views
by The go-to Tester (360 points)
retagged by
What is the @Factory annotation of TestNG and what is a use of it?

1 Answer

0 like 0 dislike
by The go-to Tester (181 points)
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.


This site is for software testing professionals, where you can ask all your questions and get answers from 1300+ masters of the profession. Click here to submit yours now!

...