In TestNG, how does @Parameters get values from testng.xml, which declaration wins on a name clash, and what does @Optional change?
answer
- names mapped by position
- four scopes, narrowest wins
- a JVM property is checked first
- fallback value or null
basics
~20 s@Parameters lists XML parameter names whose string values TestNG passes, in order, to the method's arguments. The innermost <parameter> wins (methods over class over test over suite); @Optional supplies a fallback when none is defined.
solid answer
~40 s`@Parameters({"browser"})` on a `@Test`, a configuration method, a `@Factory` method or one constructor names XML parameters; TestNG maps them to the Java arguments by position and converts the string to `String`, a primitive or wrapper, or an enum. A `<parameter name="browser" value="chrome"/>` can sit under `<suite>`, `<test>`, `<class>` or `<methods>`, and the narrowest scope wins, so a per-`<test>` value overrides the suite default. In 7.12 the lookup is `System.getProperty(name, xmlValue)`, so a JVM system property with the same name beats the file. If nothing is found, an `@Optional("chrome")` argument gets its value, a bare `@Optional` gets `null`, and without `@Optional` TestNG throws a `TestNGException` naming the missing parameter.
code
java · 11 linesimport org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class SearchTest {
@Parameters({"browser", "pageSize"})
@Test
public void searchReturnsResults(@Optional("chrome") String browser, int pageSize) {
// pageSize has no @Optional: if no source defines it, TestNG throws TestNGException
}
}go deeper
Recall that @Parameters names values defined as <parameter> elements in testng.xml and that @Optional gives a fallback.
Explain the resolution chain: system property, then methods, class, test, suite, then the @Optional value, then a TestNGException. Mention positional mapping and type conversion.
Show you can diagnose a collapsed browser matrix caused by a leftover -D property, or swapped arguments from a reordered name list.
Decide which values a team may pass as parameters versus environment configuration, and whether -D overrides are allowed in CI or pinned in the suite file.
## What @Parameters does `org.testng.annotations.Parameters` lets a method receive **simple values defined outside the code**, most often in the suite file. The annotation holds a list of parameter **names**; at run time TestNG looks each name up and passes the values to the method's arguments **in the same order as the names**. The documentation states that TestNG reports an error if the number of names and the number of Java arguments do not match. `@Parameters` can be placed on: - a `@Test` method; - a configuration method such as `@BeforeClass` or `@BeforeTest`; - a `@Factory` method; - **at most one constructor** of the test class, which TestNG then uses to instantiate it. Values are strings in the XML. TestNG converts them to the declared Java type for `String`, every primitive and its wrapper, and enums (via `Enum.valueOf`, so the case must match the constant). Any other declared type for a named parameter raises a `TestNGException` reporting an unsupported parameter type; complex objects belong in a data provider instead. ## The cross-browser pattern The classic use is one suite file that runs the same Selenium classes once per browser: ```xml <!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd"> <suite name="cross-browser"> <parameter name="baseUrl" value="https://staging.example.test"/> <test name="chrome"> <parameter name="browser" value="chrome"/> <classes><class name="com.shop.CheckoutTest"/></classes> </test> <test name="firefox"> <parameter name="browser" value="firefox"/> <classes><class name="com.shop.CheckoutTest"/></classes> </test> </suite> ``` ```java import org.testng.annotations.BeforeClass; import org.testng.annotations.Optional; import org.testng.annotations.Parameters; public class CheckoutTest { @Parameters({"browser", "baseUrl"}) @BeforeClass public void openBrowser(@Optional("chrome") String browser, String baseUrl) { // start the driver for this <test>'s browser } } ``` Each `<test>` supplies its own `browser`, and both inherit `baseUrl` from the suite. ## Where a value resolves from TestNG resolves each name through a fixed chain: 1. **A JVM system property of the same name.** The 7.12 source reads the value as `System.getProperty(name, xmlValue)`, so `-Dbrowser=firefox` overrides whatever the file says, for every `<test>` at once. 2. **The XML, narrowest scope first.** The documented precedence, lowest to highest, is `<suite>` then `<test>` then `<class>` then `<methods>`. 3. **The `@Optional` value** on that argument, if the name was found nowhere. 4. **Failure.** With no value and no `@Optional`, TestNG throws a `TestNGException` whose message says the parameter "is required by" the method "but has not been marked @Optional or defined". | Source | Wins over | Typical use | |---|---|---| | JVM system property | everything in the file | a CI job overriding one value | | `<methods>` parameter | class, test, suite | one method's special case | | `<class>` parameter | test, suite | one class's setting | | `<test>` parameter | suite | the per-browser value | | `<suite>` parameter | nothing above | run-wide defaults | | `@Optional("x")` | only an absent value | a local-run default | The system-property step surprises people: a stray `-Dbrowser` left in a run configuration silently flattens a carefully per-`<test>` matrix into one browser. ## What @Optional changes `org.testng.annotations.Optional` goes on a **method argument**. Its `value()` defaults to the sentinel string `"null"`, because annotation values cannot be `null`; TestNG converts that sentinel to a real `null`. So: - `@Optional("chrome") String browser` gets `"chrome"` when no source defines `browser`; - `@Optional String browser` gets `null`; - an `@Optional` on a primitive argument with no value would mean passing `null` to a primitive, which TestNG logs as a problem; prefer a wrapper type or an explicit default. `@Optional` is what lets a class run directly from an IDE, without the suite file, while the suite file still drives the real matrix. ## Pitfalls interviewers probe - **Positional mapping:** the first name feeds the first argument. Reordering one list without the other swaps values silently when the types match. - **Missing values fail loudly**, not as a quiet `null`, unless `@Optional` is present. - **Data providers are a different tool:** `@Parameters` carries a few strings from the file; per-row test data comes from a data provider. - **Parameters inside `<suite-file>`** are ignored, and TestNG logs that it ignored them. - **Enum values are case-sensitive:** `value="CHROME"` converts to a `Browser.CHROME` argument, but `value="chrome"` fails with a conversion `TestNGException`. - **A value of the literal string `null`** is converted to a real `null`, the same sentinel `@Optional` uses.
- A CI job passes -Dbrowser=firefox while testng.xml defines browser per <test>. What runs, and why?Every `<test>` gets `firefox`. TestNG 7.12 resolves a `@Parameters` name with `System.getProperty(name, xmlValue)`, so a JVM system property of the same name takes precedence over any `<parameter>` in the file, at every scope. The per-browser matrix collapses into one browser, and the report still shows two `<test>` names.
- Why might a TestNG @Parameters method receive its arguments in the wrong slots without any error?TestNG maps names to arguments strictly by position. If `@Parameters({"user", "password"})` is paired with `(String password, String user)`, both are strings, so conversion succeeds and the values arrive swapped. Only a count mismatch or a failed type conversion is reported.
- In TestNG, what does a bare @Optional on a String argument pass when the parameter is undefined?`null`. `@Optional`'s `value()` defaults to the sentinel string "null" because Java annotation values cannot be null, and TestNG converts that sentinel into a real `null` before calling the method.
- Thinks the suite-level parameter overrides a value set on a <test>
- Believes a missing parameter quietly arrives as null without @Optional
- Maps @Parameters names to arguments by name rather than by position
- Assumes the suite file always wins over a -D JVM system property
- Uses @Parameters to feed many rows of test data instead of a data provider
Assumes TestNG 7.12; the system-property-first lookup and the missing-parameter TestNGException were checked against the 7.12.0 source.