Answer
@Factory Annotation in TestNG
@Factory creates multiple instances of a test class at runtime. Unlike @DataProvider (which runs one method multiple times), @Factory runs the entire test class multiple times with different configurations.
Basic Example
Java
// Test class with constructor parameter
public class LoginTest {
private String username;
private String password;
private String expectedTitle;
public LoginTest(String username, String password, String expectedTitle) {
this.username = username;
this.password = password;
this.expectedTitle = expectedTitle;
}
@Test
public void loginTest() {
driver.findElement(By.id("username")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
driver.findElement(By.id("loginBtn")).click();
Assert.assertTrue(driver.getTitle().contains(expectedTitle));
}
@Test
public void verifyProfileTest() {
// Also uses this.username for profile verification
driver.findElement(By.cssSelector(".profile-name"));
Assert.assertTrue(/* profile visible */);
}
}
Factory Class
Java
public class LoginTestFactory {
@Factory
public Object[] createInstances() {
return new Object[] {
new LoginTest("admin", "admin123", "Dashboard"),
new LoginTest("manager", "mgr456", "Reports"),
new LoginTest("readonly", "read789", "View Only"),
};
}
}
testng.xml — Point to Factory, Not Test Class
XML
<suite name="MultiUserSuite">
<test name="Login As Different Users">
<classes>
<class name="factory.LoginTestFactory"/>
<!-- NOT LoginTest — factory creates those instances -->
</classes>
</test>
</suite>
Result: TestNG runs ALL @Test methods in LoginTest for EACH of the 3 users — 6 total test runs.
@Factory with @DataProvider
Java
public class BrowserFactory {
@Factory(dataProvider = "browsers")
public Object[] createBrowserInstances(String browser) {
return new Object[] { new CrossBrowserTest(browser) };
}
@DataProvider(name = "browsers")
public Object[][] browsers() {
return new Object[][] {
{"chrome"}, {"firefox"}, {"edge"}
};
}
}
@Factory vs @DataProvider
| Aspect | @DataProvider | @Factory |
|---|---|---|
| Scope | Single @Test method | Entire test class |
| Object creation | One instance, N calls | N instances of class |
| Setup/Teardown | Shared @Before/@After | Separate per instance |
| Use case | Same test, different data | Same suite, different config |
| Example | Same login test with 10 users | Entire LoginTest suite for each browser |
