In TestNG, the @Factory annotation is used to create instances of test classes dynamically at runtime, particularly when you want to run the same test class multiple times with different sets of data or configurations
.
Purpose of @Factory:
Allows creation of multiple instances of a test class.
Enables running the same tests with different input values.
Useful for data-driven testing.
Key Characteristics:
@Factoryis applied on a method, not a class.The factory method should return an array of
Object, where each object is an instance of a test class.Can be combined with constructors to pass parameters into the test class.
Example: Using @Factory in TestNG
Let's say you want to run the same test with different browser names:
Step 1: Test Class
import org.testng.annotations.Test; public class BrowserTest { private String browser; // Constructor to accept the browser name public BrowserTest(String browser) { this.browser = browser; } @Test public void openBrowserTest() { System.out.println("Running test on: " + browser); } }
import org.testng.annotations.Factory; public class BrowserTestFactory { @Factory public Object[] createInstances() { return new Object[] { new BrowserTest("Chrome"), new BrowserTest("Firefox"), new BrowserTest("Edge") }; } }
testng.xml<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" > <suite name="Browser Suite"> <test name="Browser Test Factory"> <classes> <class name="BrowserTestFactory" /> </classes> </test> </suite>
Running test on: Chrome Running test on: Firefox Running test on: Edge
When to Use @Factory:
You want to test the same functionality with different data.
You prefer passing parameters via constructors rather than using
@DataProvider.You need complex test class instantiation logic.
@Factory and @DataProvider:| Feature | @Factory | @DataProvider |
|---|---|---|
| Usage | Instantiates test classes | Feeds data to test methods |
| Applied on | Method | Method |
| Returns | Object[] (instances) | Object[][] (data sets) |
| Constructor usage | Yes | No (generally, parameters in test methods) |