In TestNG, how do you reuse one @DataProvider across test classes, and how can it tailor its rows to the calling test method?
answer
- provider living in another class
- dataProviderClass attribute
- static, or a no-arg constructor
- inject Method or ITestContext
- indices pick rows
basics
~10 sPut the provider in its own class and reference it with @Test(dataProviderClass = ..., dataProvider = ...). Declaring a java.lang.reflect.Method or ITestContext parameter on the provider lets it return different rows per calling test.
solid answer
~40 sA provider outside the test class is reached with `@Test(dataProvider = "users", dataProviderClass = UserData.class)`; the same attribute exists on `@Factory`. The javadoc says such a provider must be static, and static is the simplest choice, but since 6.9.4 TestNG will instantiate the provider class through its object factory when the method is not static, which needs a usable constructor. To tailor rows, the provider may declare parameters TestNG injects: `java.lang.reflect.Method` (the calling test method), `ITestContext` (the current `<test>`, with its groups, parameters and attributes), and a few others such as `ITestNGMethod` or `Class`. A parameter TestNG cannot inject fails as unresolved. Separately, `@DataProvider(indices = {0, 2})` runs only selected rows, counted from zero.
code
java · 28 linesimport java.lang.reflect.Method;
import java.util.Arrays;
import org.testng.ITestContext;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
class UserData {
@DataProvider(name = "users")
public static Object[][] users(Method method, ITestContext context) {
boolean smoke = Arrays.asList(context.getIncludedGroups()).contains("smoke");
if (method.getName().equals("lockedAccount")) {
return new Object[][] {{"locked-user"}};
}
return smoke
? new Object[][] {{"alice"}}
: new Object[][] {{"alice"}, {"bob"}, {"carol"}};
}
}
public class AccountTest {
@Test(dataProvider = "users", dataProviderClass = UserData.class)
public void validLogin(String user) {
}
@Test(dataProvider = "users", dataProviderClass = UserData.class)
public void lockedAccount(String user) {
}
}go deeper
Recall that dataProviderClass points a test at a provider in another class, and that static provider methods there are the safe default.
Explain which parameter types TestNG injects into a provider, how Method and ITestContext let one provider serve several tests, and that indices count from zero.
Know that the javadoc's static rule is stricter than the code, that indices still build every row, and that a non-static shared provider runs on its own instance.
Decide how much tailoring a shared provider may do before it should be split, keeping test inputs reproducible regardless of how the run was launched.
## Why share a provider In a growing TestNG suite the same data turns up in many classes: a list of user roles, supported currencies, a matrix of login credentials. Copying a `@DataProvider` into each class duplicates the data and lets the copies drift. TestNG lets a test method use a provider that lives in **another class**, and lets that provider **look at who is calling it** so one method can serve several tests. ## Referencing a provider in another class By default TestNG looks for the named provider in the test's own class and its superclasses. To use one elsewhere, name both the provider and its class: - `@Test(dataProvider = "users", dataProviderClass = UserData.class)` on a test method. - `@Factory(dataProvider = "browsers", dataProviderClass = BrowserData.class)` on a factory method or constructor. - The attributes can also sit on a class-level `@Test`, so every test method in the class inherits them. **The static question.** The `dataProviderClass` javadoc on `@Test` and `@Factory` says the provider method "needs to be static on the specified class". The source is more permissive: since 6.9.4 (CHANGES.txt, GITHUB-631), when the provider in a `dataProviderClass` is not static, TestNG creates an instance of that class through its object factory and calls the method on it. That requires a constructor TestNG can use, normally a public no-argument one. Static remains the conventional choice because it needs no instance at all and keeps the provider free of per-instance state; the documentation site states the relaxed rule as "a static method or a class with a non-arg constructor". ## Injecting the caller into the provider A provider method may declare parameters that TestNG fills in itself rather than from data: | Parameter type | What TestNG passes | |---|---| | `java.lang.reflect.Method` | the test method being fed | | `ITestContext` | the context of the current `<test>` element of the suite file | | `ITestNGMethod` | TestNG's own model of the test method, including its groups | | `Class` | the class declaring the test method | | `Constructor` | the constructor being fed, when the consumer is a factory constructor | A parameter of any other type, unless it is marked with `@TestInstance`, makes TestNG fail with a "parameters unresolved" error. The common uses are: 1. **Branch on the method**: one provider feeds `validLogin` and `lockedAccount`, and returns different rows depending on `method.getName()`. 2. **Branch on the run**: `context.getIncludedGroups()` tells the provider a smoke run is in progress, so it returns three rows instead of three hundred; `context.getCurrentXmlTest().getParameter("env")` picks a data file per environment. 3. **Share computed data**: `ITestContext` is also an attribute store (`setAttribute`/`getAttribute`) scoped to the current `<test>`. Branching should stay shallow. A provider with a long `switch` on method names is several providers pretending to be one, and is harder to read than two small providers. ## Running only some rows with indices `@DataProvider(indices = {0, 2})` restricts the run to the listed rows. Indices are **zero-based**. TestNG still calls the provider and walks every row; it discards the rows not listed. That makes `indices` a debugging and triage tool (rerun row 37 only) rather than a way to avoid building expensive rows. `@Factory` has its own `indices` attribute that does the same for the instances it creates. ## Choosing where the provider lives A reasonable split many suites settle on: - **Same class** when only that class uses the data; the reader sees rows and test together. - **A dedicated data class** referenced by `dataProviderClass` when several classes need identical rows, such as supported currencies. - **A shared superclass** when a family of test classes extends the same base; the default lookup already searches superclasses, so no extra attribute is needed. ## Pitfalls - **Name clashes**: two providers with the same name in the searched class make TestNG raise "Found two providers called". - **Hidden state**: a non-static provider in a shared class gets an instance TestNG creates; fields on it are not the test class's fields, so a provider that expects state set by a test's hooks finds none. - **Over-tailoring**: a provider that reads groups and parameters to reshape its output can make a test's input depend on how it was launched, which is hard to reproduce locally. ## Contrast with JUnit Jupiter JUnit Jupiter can also reference a factory method in another class for its parameterized tests, under its own rules; TestNG's mechanism is the `dataProviderClass` attribute plus the injected parameters above.
- Does @DataProvider(indices = ...) stop TestNG from building the rows you excluded?No. TestNG still calls the provider and walks every row, counting from zero; rows whose index is not listed are discarded before the test is invoked. It is useful for rerunning one failing row, not for saving the cost of building rows.
- What happens if a TestNG data provider declares a parameter type TestNG cannot inject, such as a String?TestNG cannot resolve it and fails with an error listing the unresolved parameters and their positions. Providers receive only the types TestNG injects, such as `Method`, `ITestContext`, `ITestNGMethod`, `Class` or a `@TestInstance` parameter, not suite-file values bound by name.
- A provider can only be used by test methods in its own class
- TestNG can inject any argument type into a data provider method
- Data provider indices are counted from one, like row numbers in a spreadsheet
- indices skips building the excluded rows, so it saves expensive setup
- ITestContext in a provider describes the whole suite run rather than the current test element
Assumes TestNG 7.12; non-static methods in a dataProviderClass have been instantiated by TestNG since 6.9.4, although the javadoc still says static.