ScreenshotNeo

BlogHow-to

How to Access Test Fields from a TestNG IInvokedMethodListener

Use ITestResult.getInstance() to reach the current TestNG test object, distinguish test methods from configuration callbacks, and avoid common listener errors.

By the ScreenshotNeo team30 September 20266 min read

How to Access Test Fields from a TestNG IInvokedMethodListener

Use ITestResult.getInstance() inside beforeInvocation or afterInvocation. It returns the object on which the invoked method ran. Type-check or cast that object to your test class, then read the field through a suitable accessor.

import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ITestResult;

public final class FieldListener implements IInvokedMethodListener {
    @Override
    public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
        if (!method.isTestMethod()) {
            return; // Also called for configuration methods.
        }

        Object instance = testResult.getInstance();
        if (instance instanceof CheckoutTest) {
            CheckoutTest test = (CheckoutTest) instance;
            System.out.println("Account: " + test.getAccountId());
        }
    }

    @Override
    public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
        if (!method.isTestMethod()) {
            return;
        }

        Object instance = testResult.getInstance();
        if (instance instanceof CheckoutTest) {
            CheckoutTest test = (CheckoutTest) instance;
            System.out.println("Finished account: " + test.getAccountId());
        }
    }
}

TestNG documents ITestResult.getInstance() as “The instance on which this method was run.” The result also provides the invoked method, parameters, test class, and status. See the ITestResult API.

Complete example

1. Create a test class with state

import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

@Listeners(FieldListener.class)
public class CheckoutTest {
    private String accountId;

    @BeforeMethod
    public void setUp() {
        accountId = "acct-42";
    }

    public String getAccountId() {
        return accountId;
    }

    @Test
    public void canCheckout() {
        Assert.assertNotNull(accountId);
    }
}

2. Implement the listener

import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ITestResult;

public class FieldListener implements IInvokedMethodListener {
    @Override
    public void beforeInvocation(IInvokedMethod method, ITestResult result) {
        if (!method.isTestMethod()) {
            return;
        }

        Object instance = result.getInstance();
        if (!(instance instanceof CheckoutTest)) {
            return;
        }

        CheckoutTest test = (CheckoutTest) instance;
        System.out.println("beforeInvocation: " + test.getAccountId());
        System.out.println("parameters: " + java.util.Arrays.toString(result.getParameters()));
    }

    @Override
    public void afterInvocation(IInvokedMethod method, ITestResult result) {
        if (!method.isTestMethod()) {
            return;
        }

        CheckoutTest test = (CheckoutTest) result.getInstance();
        System.out.println("status=" + result.getStatus()
                + ", account=" + test.getAccountId());
    }
}

3. Register through testng.xml instead

Use either @Listeners or XML registration. XML is useful when you do not want to modify test source files.

The listener receives ITestResult, whose instance points to the object that ran the method.
The listener receives ITestResult, whose instance points to the object that ran the method.
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Checkout suite">
  <listeners>
    <listener class-name="FieldListener"/>
  </listeners>
  <test name="Checkout tests">
    <classes>
      <class name="CheckoutTest"/>
    </classes>
  </test>
</suite>

TestNG supports both registration styles. The listener guide explains listener registration and notes that @Listeners applies to the suite file; filter inside the callback when only certain methods should be handled. See TestNG documentation.

How the callback arguments fit together

Value Use it for
ITestResult.getInstance() The test object on which the current method ran.
ITestResult.getParameters() Arguments supplied to this invocation, including data-provider values.
ITestResult.getMethod() Method metadata and TestNG method information.
IInvokedMethod.isTestMethod() Determine whether the callback concerns an @Test method.
IInvokedMethod.isConfigurationMethod() Determine whether it concerns setup or teardown configuration.
ITestResult.getStatus() Read pass, failure, or skip status after invocation.

IInvokedMethodListener receives notifications for test methods and configuration methods such as @BeforeMethod and @AfterMethod. Always classify the invocation before reading test-only state. The IInvokedMethodListener API and IInvokedMethod API describe these callback types.

Fields, access modifiers, and inheritance

  • Public or package-private field: read it directly when Java access rules allow it.
  • Private field: expose a getter or another intentional method. Prefer a getter over reflection because it preserves encapsulation.
  • Superclass field: the cast object still contains inherited state; access it through an inherited getter or field allowed by Java visibility.
  • Multiple test classes: use instanceof checks, a shared interface, or a common base class.
public interface HasAccountId {
    String getAccountId();
}

public class FieldListener implements IInvokedMethodListener {
    @Override
    public void beforeInvocation(IInvokedMethod method, ITestResult result) {
        if (!method.isTestMethod()) {
            return;
        }

        Object instance = result.getInstance();
        if (instance instanceof HasAccountId) {
            String accountId = ((HasAccountId) instance).getAccountId();
            System.out.println(accountId);
        }
    }
}

Test fields versus method parameters

A field belongs to the test object returned by getInstance(). A data-provider value belongs to the invocation and is returned by getParameters(). They are different sources of state.

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class ParameterizedTest implements HasAccountId {
    private final String accountId = "acct-99";

    @Override
    public String getAccountId() {
        return accountId;
    }

    @DataProvider
    public Object[][] users() {
        return new Object[][] { { "alice" }, { "bob" } };
    }

    @Test(dataProvider = "users")
    public void loadsUser(String username) {
        System.out.println(username);
    }
}

In the listener, result.getParameters()[0] is the username, while ((ParameterizedTest) result.getInstance()).getAccountId() is the field-backed value.

Alternative access path

When the method representation is the one your code needs, TestNG also exposes an instance through method.getTestMethod().getInstance():

Fields come from getInstance(); invocation arguments come from getParameters().
Fields come from getInstance(); invocation arguments come from getParameters().
Object instance = method.getTestMethod().getInstance();

For ordinary listener code, prefer result.getInstance() because it is explicitly tied to the current invocation result. The ITestNGMethod API documents the alternative accessor.

Configuration callbacks and ordering

beforeInvocation can run before a test method, a setup method, or a teardown method. If a field is initialized in @BeforeMethod, do not expect it to be populated when the listener observes that @BeforeMethod invocation itself. It should be available when the subsequent test invocation occurs.

@Override
public void beforeInvocation(IInvokedMethod method, ITestResult result) {
    if (method.isConfigurationMethod()) {
        System.out.println("Configuration: " + method.getTestMethod().getMethodName());
        return;
    }

    if (method.isTestMethod()) {
        // Safe place for test-method-specific field handling.
    }
}

Common errors and fixes

Symptom Cause Fix
ClassCastException The listener is attached to more than one test class. Use instanceof, a shared interface, or a base type before casting.
Field is null Initialization has not run yet, or the field is reset in teardown. Check callback type and lifecycle order; read it during the test-method callback.
Listener runs for setup and teardown That is expected behavior. Guard test-only logic with method.isTestMethod().
Data-provider value is missing The code reads the object field instead of invocation parameters. Use result.getParameters().
Listener never fires for skipped tests Runner configuration may disable skipped-test callbacks. Check the TestNG version and alwaysRunListeners settings in the command line, build tool, or suite configuration.
getInstance() is not the expected type A factory, inherited test, or another suite class supplied the instance. Log instance.getClass() and support the actual type or common interface.

Reliability and performance practices

  • Keep listener work small. It runs around every matching invocation and can slow a large suite.
  • Do not mutate test fields from the listener unless that mutation is part of a documented lifecycle contract.
  • Use thread-safe sinks when the suite runs in parallel. Avoid shared mutable fields in the listener itself.
  • Prefer stable interfaces over a long list of concrete test-class casts.
  • Guard against null before logging or dereferencing an instance supplied by custom runners.
  • For diagnostics, include method name, instance type, parameters, and result status rather than dumping sensitive field values.

Version and runner caveats

The cited API references are for TestNG 7.9.0, with invocation details also checked against 7.0.0. Confirm signatures and skipped-callback behavior against the version and runner used by your project. TestNG’s documentation states that listener callbacks cover configuration and test methods, while skipped callbacks can be disabled through alwaysRunListeners mechanisms.

Or skip the browser setup

If your workflow also needs screenshots of test reports or application pages, ScreenshotNeo provides a single HTTP request instead of maintaining browser setup. Cookie banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result. Its MCP server lets Claude, Cursor, and other MCP clients call take_screenshot, get_page_info, and capture_pdf.

See the ScreenshotNeo API documentation for all options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo includes 1,000 screenshots a month free with no card. Paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

FAQ

How do I get the current test object in beforeInvocation?

Call testResult.getInstance(), then type-check or cast the returned object.

Can I read a private field directly?

No. Use a getter or another method on the test class. Reflection is possible but usually makes the listener more fragile.

Why does my listener see setup methods?

TestNG invokes the listener for configuration methods as well as @Test methods. Check method.isTestMethod() and method.isConfigurationMethod().

Should I use getParameters() for a field?

No. Use getParameters() for data-provider or invocation arguments; use getInstance() for fields on the test object.