How to use @Factory Annotation in TestNG

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:

  • @Factory is 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);
    }
}




Step 2: Factory Class

import org.testng.annotations.Factory;

public class BrowserTestFactory {

    @Factory
    public Object[] createInstances() {
        return new Object[] {
            new BrowserTest("Chrome"),
            new BrowserTest("Firefox"),
            new BrowserTest("Edge")
        };
    }
}



Step 3: 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>



Output:

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.




Difference Between @Factory and @DataProvider:

Feature@Factory@DataProvider
UsageInstantiates test classesFeeds data to test methods
Applied onMethodMethod
ReturnsObject[] (instances)Object[][] (data sets)
Constructor usageYesNo (generally, parameters in test methods)

No comments:

Post a Comment