skip to content

In a TestNG @AfterMethod hook, how do you find out which test method just ran and whether it passed, failed or was skipped?

level: middleimportance: should knowfreq 42%

answer

  1. declare a parameter, TestNG fills it
  2. native injection
  3. status as an int constant
  4. Method for the upcoming test

basics

~10 s

Declare an ITestResult parameter on the @AfterMethod method: TestNG injects the result of the test method that just ran, so getStatus(), getMethod() and getThrowable() give the outcome, the method and any exception.

solid answer

~40 s

TestNG supports **native injection**: a configuration method declares a parameter of a type TestNG knows, and TestNG fills it. An `@AfterMethod` method can take an `ITestResult`, which reflects the test method that was just run. `getStatus()` returns an int compared against `ITestResult.SUCCESS`, `ITestResult.FAILURE` or `ITestResult.SKIP`, `isSuccess()` gives a boolean, `getMethod()` and `getName()` identify the test, and `getThrowable()` returns the failure's exception. A `java.lang.reflect.Method` parameter works too, naming the test method after it has run, and in a `@BeforeMethod` naming the one about to run. Mark the hook `alwaysRun = true` if it must also see tests skipped by a failed setup. `ITestResult` is not injectable into class-level or wider hooks; a listener is the alternative when the logic should apply across many classes.

code

java · 27 lines
java
import java.lang.reflect.Method;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class OrderApiTest {
  @BeforeMethod
  public void announce(Method testMethod) {
    System.out.println("starting " + testMethod.getName());
  }

  @Test
  public void createsOrder() { }

  @AfterMethod(alwaysRun = true)
  public void recordOutcome(ITestResult result) {
    String name = result.getMethod().getMethodName();
    if (result.getStatus() == ITestResult.FAILURE) {
      System.out.println(name + " failed: " + result.getThrowable());
    } else if (result.getStatus() == ITestResult.SKIP) {
      System.out.println(name + " skipped: " + result.getThrowable());
    } else if (result.isSuccess()) {
      System.out.println(name + " passed");
    }
  }
}

go deeper

for a junior

Remember the move: add an ITestResult parameter to @AfterMethod and TestNG fills it with the outcome of the test that just ran.

for a middle

Explain native injection, which types each hook accepts, the int status constants, and why Method in @BeforeMethod names the upcoming test.

for a senior

Show where it goes wrong: a result hook that misses skipped tests for lack of alwaysRun, or evidence capture placed in a class-level hook that cannot see results.

for a principal

Be ready to decide where per-test reactions live, in a shared hook for one class hierarchy or a listener for the whole suite, and what each costs to maintain.

## Native injection in TestNG TestNG lets a method declare extra parameters of certain framework types, and fills them automatically. TestNG calls this **native dependency injection**, to distinguish it from injection by an external container. Which types a method may declare depends on its annotation. For the method-level hooks, the documentation's table lists: | Type | `@BeforeMethod` | `@AfterMethod` | What it holds | |---|---|---|---| | `ITestResult` | yes | yes | the result of the test invocation; in `@AfterMethod`, the one just run | | `java.lang.reflect.Method` | yes | yes | the test method about to run, or that just ran | | `Object[]` | yes | yes | the parameters fed to that test invocation | | `ITestContext` | yes | yes | the state of the current `<test>` element | | `XmlTest` | yes | yes | the current `<test>` element of the suite file | `@BeforeClass`, `@BeforeTest` and their `@After` pairs accept only `ITestContext` and `XmlTest`, so `ITestResult` and `Method` are method-level tools. ## Reading the outcome An `ITestResult` describes one invocation of one test method. The members used in an `@AfterMethod` hook are: - `getStatus()` returns an `int`. Compare it with the constants on the interface: `ITestResult.SUCCESS` (1), `ITestResult.FAILURE` (2), `ITestResult.SKIP` (3) and `ITestResult.SUCCESS_PERCENTAGE_FAILURE` (4). - `isSuccess()` returns a boolean for the common "did it pass" check. - `getMethod()` returns the `ITestNGMethod`, and `getName()` the method name. - `getThrowable()` returns the exception of a failed invocation; for a test skipped by a failed configuration method it carries that method's exception. - `getParameters()` returns the arguments the invocation received, useful for data-driven tests. The status is an `int`, not a boolean or an enum, so compare it with the named constants rather than with literals. ## Typical uses 1. **Capture evidence only on failure.** Check `getStatus() == ITestResult.FAILURE` and save a screenshot, a response body or a log excerpt while the state still exists. Doing it in `@AfterMethod` keeps it next to the code that created that state. 2. **Log per-test outcomes** with the method name and parameters, so a long run's console tells you which data row failed. 3. **Clean up differently by outcome**, for example keeping a failed test's temporary files for inspection and deleting a passed test's. 4. **Name the upcoming test in setup** with a `Method` parameter in `@BeforeMethod`, for example to label a log section or a recorded session. ## Passing data from the test to the hook `ITestResult` extends TestNG's `IAttributes`, so it carries `setAttribute` and `getAttribute`. A test can reach its own result through `Reporter.getCurrentTestResult()` and attach a value, such as the id of an order it created; the `@AfterMethod` hook then reads it from the injected result and deletes that order. This keeps cleanup data out of shared fields, which matters once methods of the same instance run on different threads. ## Make it see skips too A hook that inspects results usually wants to see **every** outcome, including tests skipped because a configuration method failed. Under the default `configfailurepolicy="skip"`, those skips cascade to the `@AfterMethod` hook itself unless it is marked `alwaysRun = true`. Without the flag, the hook silently misses exactly the tests that were blocked by broken setup. ## When a hook is the wrong place An `@AfterMethod` hook applies to the class that declares it and to its subclasses. When the same reaction must apply to every class in the suite, TestNG's listener interfaces are the usual alternative; they receive the same `ITestResult` objects, but belong to the listener mechanism rather than to configuration hooks. In an interview it is enough to name that boundary: hook for one class hierarchy, listener for the whole run. ## Mistakes to avoid - Declaring `ITestResult` on `@AfterClass`: it is not injectable there, and TestNG rejects the parameter. - Comparing `getStatus()` with a magic number instead of the constants. - Assuming the hook sees skipped tests without `alwaysRun = true`. - Expecting a `Method` parameter in `@BeforeMethod` to name the hook; it names the test method about to run. ## Contrast with JUnit Jupiter JUnit Jupiter has its own way to give hooks information about the running test, through its extension and parameter-resolution model, covered with that framework. In TestNG the answer is the injected `ITestResult` and `Method` parameters described here.

  • In TestNG, what does an Object[] parameter on a @BeforeMethod hook receive, and when is it useful?
    It receives the parameters about to be fed to the upcoming test invocation, whether they come from a data provider or are injected by TestNG. It is useful for logging or preparing state per data row before that row's test runs.
  • A TestNG @AfterMethod(ITestResult result) hook never logs the tests that a failed @BeforeMethod blocked. Why?
    Under the default `configfailurepolicy="skip"`, the setup failure also skips the teardown hooks that depend on it, so the hook never runs for those tests. Adding `alwaysRun = true` to the `@AfterMethod` makes it run and see their SKIP status.

  • Reading a test's status in TestNG requires writing a listener.
  • ITestResult can be injected into @BeforeClass or @AfterClass.
  • ITestResult.getStatus() returns a boolean pass or fail flag.
  • A plain @AfterMethod sees tests skipped by a failed setup.
  • A Method parameter on @BeforeMethod receives the hook method itself.