</>

Technology

TestNG

Difficulty

Advanced

Interview Question

What is the @Factory annotation in TestNG and when do you use it?

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
ScopeSingle @Test methodEntire test class
Object creationOne instance, N callsN instances of class
Setup/TeardownShared @Before/@AfterSeparate per instance
Use caseSame test, different dataSame suite, different config
ExampleSame login test with 10 usersEntire LoginTest suite for each browser

Follow AutomateQA

Related Topics