Purpose of @Factory Annotation in TestNG

What is the use of @Factory annotation in TestNG?

1 Like

Hey Darran,

The key to dynamic test case execution in TestNG is the use of the “@Factory” annotation. This annotation allows you to inject parameters into the entire test class at runtime. This allows you to create flexible and custom test scenarios. This is especially useful when you need to execute the same set of tests with different inputs or different configurations

For instance, consider the scenario involving two classes: TestClass and TestFactory. Through the application of the @Factory annotation, the test methods within TestClass can be orchestrated to run multiple times, each with distinct data values. In the provided example, the TestFactory class utilizes @Factory to generate instances of TestClass with parameters “K1” and “k2,” resulting in the execution of the TestMethod twice, once with each set of data.

public class TestClass {
    private String str;

    // Constructor
    public TestClass(String str) {
        this.str = str;
    }

    @Test
    public void TestMethod() {
        System.out.println(str);
    }
}

public class TestFactory {
    // The test methods in class TestClass will run twice with data "K1" and "k2"
    @Factory
    public Object[] factoryMethod() {
        return new Object[] { new TestClass("K1"), new TestClass("k2") };
    }
}

In this way, the @Factory annotation provides an elegant solution for parameterized testing, enhancing the flexibility and efficiency of test suites in TestNG.

Thanks for your question! We’re always here to help, so ask away anytime.