skip to content

In TestNG, what does @Factory do, when would you choose it over a @DataProvider, and how can the two be combined?

level: middleimportance: must knowfreq 56%

answer

  1. instances, not invocations
  2. returns Object[] of test objects
  3. constructor plus dataProvider
  4. class hooks run per instance

basics

~20 s

@Factory creates test-class instances at run time and TestNG runs every @Test method on each. A @DataProvider repeats one method per row; a factory repeats a whole class, and @Factory(dataProvider = ...) on a constructor joins them.

solid answer

~40 s

A `@DataProvider` invokes one test method once per row on the same test instance. A `@Factory` method returns `Object[]` of test objects, and TestNG treats each object as an instance of its class: all its `@Test` methods run on it and `@BeforeClass`/`@AfterClass` run once per instance. I'd choose a factory when the parameter changes the whole class's context, say one instance per browser and locale pair holding its own session in fields, and a provider when only one method's input varies. They combine in two ways: `@Factory(dataProvider = "pairs")` on a constructor builds one instance per provider row, and the test methods of those instances can still use their own providers, multiplying instances by rows.

code

java · 41 lines
java
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;

public class CheckoutTest {
  private final String browser;
  private final String locale;

  @Factory(dataProvider = "pairs")
  public CheckoutTest(String browser, String locale) {
    this.browser = browser;
    this.locale = locale;
  }

  @DataProvider
  public static Object[][] pairs() {
    return new Object[][] {
      {"chrome", "en-US"},
      {"firefox", "de-DE"},
    };
  }

  @BeforeClass
  public void openSession() {
    // runs once per instance: open a session for this browser and locale
  }

  @Test
  public void cartShowsLocalisedPrice() {
  }

  @Test
  public void paymentPageLoads() {
  }

  @AfterClass
  public void closeSession() {
  }
}

go deeper

for a junior

Recall that @Factory returns test objects and TestNG runs every @Test method on each, while @DataProvider repeats one method per row.

for a middle

Explain per-instance class hooks, the constructor form with dataProvider, why that provider is static, and how instances multiply with method-level providers.

for a senior

Show judgment on when per-instance context justifies a factory, and on the result explosion and naming problem a factory plus provider creates.

for a principal

Frame the choice as test-context design: a factory makes the context explicit per instance, at the cost of more instances to schedule, name and report.

## Two ways to multiply tests TestNG offers two mechanisms for running the same test code over different inputs, and interviewers ask for the difference because they multiply different things. - A **`@DataProvider`** multiplies **invocations of one method**. The test class is instantiated once; the method runs once per row with that row's arguments. - A **`@Factory`** multiplies **instances of a class**. Each object the factory returns is a separate test-class instance, and TestNG runs every `@Test` method on every instance, with the class-level hooks around each one. ## How @Factory works `@Factory` can sit on a **method** or on a **constructor**. 1. On a method, the method must return `Object[]` (or `IInstanceInfo[]`). Each element becomes a test instance. The elements may be of any class, not necessarily the factory's own, and objects without TestNG annotations are simply ignored. 2. On a constructor, it is combined with a provider: `@Factory(dataProvider = "pairs")` makes TestNG call the constructor once per provider row, each call producing one instance. The suite file references the class that holds the factory, and the instances themselves are created at run time. Some behaviours follow from "each object is an instance": - **Class hooks run per instance**: `@BeforeClass` and `@AfterClass` run once for each factory-created instance, not once for the class. - **State lives in fields**: constructor arguments are stored in fields that every test method of that instance reads. - **`indices`**: `@Factory(indices = {...})` keeps only the instances at the listed zero-based positions. - **`enabled`**: `@Factory(enabled = false)` switches a factory off. - **No instances is flagged**: TestNG records a message for a factory method that returns an empty array, saying it should have produced at least one instance. ## Choosing between them | Question | `@DataProvider` | `@Factory` | |---|---|---| | What repeats? | one test method | every test method of a class | | Where does the input arrive? | method parameters | constructor arguments, kept in fields | | Class hooks per input? | no, the class runs once | yes, once per instance | | Typical fit | many input rows for one check | one context (browser, locale, tenant) for a whole class of checks | The reserved example is a UI suite that must run its checkout class under each **browser and locale pair**. With a provider, every test method would need the pair as parameters and would have to open its own session. With a constructor factory, each instance receives one pair, opens its session in `@BeforeClass`, and every test method of that instance uses it; the next instance gets the next pair. A provider is the better fit when only the input data varies and the surrounding context is the same: a login form checked with a few hundred credential rows needs one instance and many invocations, not a few hundred instances. ## Combining them The two compose: - **Factory fed by a provider**: `@Factory(dataProvider = "pairs")` on the constructor, with a provider returning one row per browser and locale pair. Because no instance exists when the provider is called, keep that provider `static` (or reference one in another class with `dataProviderClass`). - **Provider inside factory instances**: a test method of a factory-built instance can declare `@Test(dataProvider = "logins")`. TestNG then runs instances times rows: three browser instances and four login rows give twelve invocations of that method. This multiplication is exactly why the combination needs restraint; the count of results grows fast, and a report needs a way to tell instances apart. ## A common mistake: work in the constructor TestNG calls factory methods and factory constructors while it is **building the instances**, before any test method or class hook of the run starts. Opening a browser session in the constructor therefore opens every session up front, all at once, and an exception there breaks instance creation rather than failing one test. Keep the constructor to storing arguments in fields, and put the expensive setup in `@BeforeClass`, which runs per instance just before that instance's tests. ## Related settings owned elsewhere Whether factory instances run concurrently is a suite-file decision (`parallel="instances"` and its thread count), not something `@Factory` itself controls. JUnit Jupiter's nearest counterpart for runtime-generated tests is its `@TestFactory`, which produces dynamic tests rather than class instances.

  • Why must the provider feeding a TestNG constructor @Factory usually be static?
    TestNG calls the provider before any instance of the class exists, because the provider's rows are the constructor's arguments. A static method needs no instance. A non-static one would need TestNG to build an instance first, which a class whose only constructor is the factory constructor cannot offer.
  • How many times does @BeforeClass run when a TestNG @Factory creates three instances of a class?
    Three times, once per instance. TestNG tracks which instances have already had their class-level hooks run, so each factory-built instance gets its own @BeforeClass before its first test method and its own @AfterClass after its last.

A data provider is one cook making the same dish with different ingredients in one kitchen; a factory opens a separate kitchen per cuisine, each with its own setup, where the whole menu is cooked.

  • @Factory and @DataProvider are interchangeable names for the same feature
  • @BeforeClass runs only once no matter how many instances a factory creates
  • A factory method may return any collection, such as a List of instances
  • Objects returned by a factory must be instances of the factory's own class
  • A factory automatically runs its instances in parallel