Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Use the ITestResult passed to beforeInvocation or afterInvocation. Its getInstance() method returns the test object on which the current method ran; type-check or cast that object, then read the field. Guard the code with method.isTestMethod() when you only want test methods, because the listener also receives configuration-method invocations.

The direct solution

A listener receives both an IInvokedMethod and an ITestResult. The result is the clearest source for the current test instance:

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

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

        Object instance = testResult.getInstance();
        if (instance instanceof LoginTest) {
            LoginTest test = (LoginTest) instance;
            System.out.println("Current user: " + test.userName);
        }
    }

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

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

ITestResult.getInstance() is documented as “The instance on which this method was run.” The returned type is Object, so the listener must use a type check, a cast, or another deliberate dispatch strategy before accessing class fields.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A complete example with a test field

Test class

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

@Listeners(FieldListener.class)
public class LoginTest {
    public String userName = "[email protected]";

    @Test
    public void opensTheDashboard() {
        System.out.println("Running as " + userName);
    }
}

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 current = result.getInstance();
        if (!(current instanceof LoginTest)) {
            return;
        }

        LoginTest test = (LoginTest) current;
        System.out.println("Before " + method.getTestMethod().getMethodName()
                + ": " + test.userName);
    }

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

        Object current = result.getInstance();
        if (current instanceof LoginTest) {
            LoginTest test = (LoginTest) current;
            System.out.println("After: " + test.userName
                    + ", status=" + result.getStatus());
        }
    }
}

The field can be private if the listener uses a getter or another intentionally exposed API. Avoid making production test state public solely for a listener; a package-private accessor, interface, or small listener-facing method is usually easier to maintain.

#1 Best Overall
Amazon Basics Wired QWERTY Keyboard, Works with Windows, Plug and Play, Easy to Use with Media Control, Full-Sized, Black
  • KEYBOARD: The keyboard works for Windows with hot keys that enable easy access to Media, My Computer, Mute, Volume up/down, and Calculator
  • EASY SETUP: Experience simple installation with the USB wired connection
  • VERSATILE COMPATIBILITY: This keyboard is designed to work with multiple Windows versions, including Vista, 7, 8, 10 offering broad compatibility across devices.
  • SLEEK DESIGN: The elegant black color of the wired keyboard complements your tech and decor, adding a stylish and cohesive look to any setup without sacrificing function.
  • FULL-SIZED CONVENIENCE: The standard QWERTY layout of this keyboard set offers a familiar typing experience, ideal for both professional tasks and personal use.

Do not confuse fields with invocation parameters

Fields on the test object

result.getInstance() identifies the object whose method is running. Its fields represent state stored on that test instance, such as a driver, test-user object, or scenario identifier.

Arguments passed to the method

result.getParameters() returns the arguments for this invocation. These commonly come from a data provider and are not fields on the test object.

public class SearchTest {
    private final String environment = "staging";

    @Test(dataProvider = "queries")
    public void searches(String query) {
        // query is an invocation parameter; environment is an instance field.
    }
}

Object testObject = result.getInstance();
Object[] arguments = result.getParameters();

Use the instance for object state and the parameter array for data-provider values. Casting a parameter to the test class, or expecting a field to appear in getParameters(), produces the wrong model of the callback.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why the method.isTestMethod() guard matters

IInvokedMethodListener is notified for methods annotated with @Test and for configuration methods such as @BeforeMethod, @BeforeClass, @AfterMethod, and @AfterClass. A configuration callback may have a different purpose, different state, or a different declaring class.

Rank #2
Sale
Logitech MK270 Full Size Wireless Keyboard and Mouse Combo - Black
  • Reliable Plug and Play: The USB receiver provides a reliable wireless connection up to 33 ft (1), so you can forget about drop-outs and delays and you can take it wherever you use your computer
  • Type in Comfort: The design of this keyboard creates a comfortable typing experience thanks to the low-profile, quiet keys and standard layout with full-size F-keys, number pad, and arrow keys
  • Durable and Resilient: This full-size wireless keyboard features a spill-resistant design (2), durable keys and sturdy tilt legs with adjustable height
  • Long Battery Life: MK270 combo features a 36-month keyboard and 12-month mouse battery life (3), along with on/off switches allowing you to go months without the hassle of changing batteries
  • Easy to Use: This wireless keyboard and mouse combo features 8 multimedia hotkeys for instant access to the Internet, email, play/pause, and volume so you can easily check out your favorite sites

Run logic only for tests

if (!method.isTestMethod()) {
    return;
}
Object instance = result.getInstance();

Handle configuration methods deliberately

if (method.isConfigurationMethod()) {
    Object instance = result.getInstance();
    // Apply setup/teardown-specific logic here.
    return;
}

if (method.isTestMethod()) {
    Object instance = result.getInstance();
    // Apply test-only logic here.
}

Do not assume that every callback can be cast to one test class. If several test classes use the listener, dispatch by interface, class, annotation, or method metadata rather than by an unconditional cast.

Alternative access path: the invoked method metadata

TestNG also exposes an instance through the ITestNGMethod returned by method.getTestMethod():

Object instance = method.getTestMethod().getInstance();

This is a valid route when your code is already working with the TestNG method representation. In listener callbacks, result.getInstance() is normally preferable because the result is the object associated with this particular invocation and is already supplied as an argument. Both approaches should still be treated as nullable or version-sensitive at integration boundaries.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Path What it represents Best use
result.getInstance() The object on which the current method ran Default choice for listener field access
method.getTestMethod().getInstance() Instance exposed through TestNG method metadata Code already centered on ITestNGMethod

Registering the listener

With @Listeners

import org.testng.annotations.Listeners;

@Listeners(FieldListener.class)
public class LoginTest {
    // tests
}

TestNG’s listener documentation describes this annotation as applying to the suite file, so treat it as suite-wide rather than as a narrow method annotation. If the listener should apply only to selected classes, enforce that scope in the listener or use XML registration boundaries that match your build.

Rank #3
Sale
Logitech K120 Full Size Wired Keyboard USB Plug-and-Play Windows - Black
  • All-day Comfort: The design of this standard keyboard creates a comfortable typing experience thanks to the deep-profile keys and full-size standard layout with F-keys and number pad
  • Easy to Set-up and Use: Set-up couldn't be easier, you simply plug in this corded keyboard via USB on your desktop or laptop and start using right away without any software installation
  • Compatibility: This full-size keyboard is compatible with Windows 7, 8, 10 or later, plus it's a reliable and durable partner for your desk at home, or at work
  • Spill-proof: This durable keyboard features a spill-resistant design (1), anti-fade keys and sturdy tilt legs with adjustable height, meaning this keyboard is built to last
  • Plastic parts in K120 include 51% certified post-consumer recycled plastic*

With testng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="example">
  <listeners>
    <listener class-name="example.FieldListener"/>
  </listeners>
  <test name="login">
    <classes>
      <class name="example.LoginTest"/>
    </classes>
  </test>
</suite>

Choose one registration strategy that fits the project. Duplicate registration can make every callback appear more than once.

Timing, status, and skipped tests

beforeInvocation runs before the invoked test or configuration method, while afterInvocation runs afterward. The same getInstance() pattern applies in both callbacks. In afterInvocation, the result also exposes status and method information, which is useful for diagnostics that should happen only after execution.

TestNG 7.9.0 documents callbacks for configuration and test methods regardless of pass, failure, or skip, but notes that skipped-test callbacks can be disabled through alwaysRunListeners settings supplied by the command line, build tool, or TestNG configuration. Verify this behavior against the TestNG version and runner used by your build before relying on callbacks for cleanup or reporting.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Common failures and fixes

ClassCastException

Cause: The listener receives a different test class or a configuration invocation. Fix: check method.isTestMethod() and use instanceof, an interface, or a class-specific branch before casting.

Rank #4
Redragon K521 Upgrade Rainbow LED Gaming Keyboard, 104 Keys Wired Mechanical Feeling Keyboard with Multimedia Keys, One-Touch Backlit, Anti-Ghosting, Compatible with PC, Mac, PS4/5, Xbox
  • 【Dreamy Rainbow Gaming Keyboard】K521 Gaming Keyboard Adopts a Different LED Backlight Design, Upgraded on the Traditional LED Backlight Effect, Making the Light More Penetrating, Giving You a More Dazzling Visual Effect, Making Your Gaming Process More Enjoyable
  • 【One Touch Opens & Visual Feast】The K521 Red Dragon Keyboard has a One-Touch on/off Lighting Button for Added Convenience. It also has a Three-Position Adjustable Breathing Mode and a Four-Position Adjustable Brightness Lighting Mode
  • 【Mechanical Feeling & Fast Tapping】The PC Keyboard Keys are Designed for Mechanical Feeling, Giving You a Better Feel During Use and the Ability to Trigger Keys Quickly, Allowing You to Win All Your Games
  • 【19 Keys Anti-Ghosting Keyboard】Anti-Ghosting Ensures Every Button Can Be Triggered. This Allows You to Trigger Key Combinations In The Game Accurately, And Each Skill Can Be Accurately Released to Increase Your Winning Rate. Redragon K521 Will Be Your Perfect Partner
  • 【12 Multimedia Combination Keys】The K521 Wired Gaming Keyboard is Equipped with 12 Multimedia Keys That Can Greatly Enhance Your Gaming/Office Efficiency and Make It More Convenient to Use

The field is always null

Cause: The field has not been initialized when beforeInvocation runs, or the listener is reading a different instance. Fix: initialize it in the appropriate configuration method, inspect the object returned by getInstance(), and avoid assuming one global test object when TestNG creates multiple instances.

The value is missing from getParameters()

Cause: The value is a field, not an invocation argument. Fix: read it from the cast test instance; use getParameters() only for arguments passed to the method.

The listener never fires for a skipped test

Cause: Listener execution for skipped tests may be disabled by alwaysRunListeners or by runner-specific configuration. Fix: inspect the effective TestNG command-line, build-plugin, and XML settings, then confirm the exact TestNG version’s behavior.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Callbacks appear twice

Cause: The listener was registered both with @Listeners and in XML, or two discovery mechanisms loaded it. Fix: keep one registration path and log the listener class and method name while diagnosing.

Best Value
Sale
Logitech K270 Full Size Wireless Keyboard for Windows - Black
  • All-day Comfort: This USB keyboard creates a comfortable and familiar typing experience thanks to the deep-profile keys and standard full-size layout with all F-keys, number pad and arrow keys
  • Built to Last: The spill-proof (2) design and durable print characters keep you on track for years to come despite any on-the-job mishaps; it’s a reliable partner for your desk at home, or at work
  • Long-lasting Battery Life: A 24-month battery life (4) means you can go for 2 years without the hassle of changing batteries of your wireless full-size keyboard
  • Simply plug the USB receiver into a USB port on your desktop, laptop or netbook computer and start using the keyboard right away without any software installation
  • Simply Wireless: Forget about drop-outs and delays thanks to a strong, reliable wireless connection with up to 33 ft range (5); K270 is compatible with Windows 7, 8, 10 or later

Reflection is used unnecessarily

Cause: Code searches for fields by name even though the test type is known. Fix: prefer a typed interface or accessor. Reflection should be reserved for intentionally generic tooling and must account for visibility, inheritance, absent fields, and security constraints.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Version and design considerations

  • The API references here correspond to TestNG 7.9.0, with invocation interfaces also documented in earlier TestNG API versions. Confirm signatures and nullability when upgrading.
  • Keep listener work lightweight. Expensive I/O in every callback slows the suite and can obscure the original test failure.
  • Do not mutate test fields from a listener unless the lifecycle contract requires it. Parallel execution can expose races when multiple instances or invocations share mutable state.
  • Prefer immutable diagnostic values, thread-safe collectors, and clear ownership of resources created in setup methods.

Or skip the browser setup:

If your listener workflow also needs repeatable website screenshots for diagnostics, ScreenshotNeo provides a single HTTP request instead of browser automation. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; bot checks, blank pages, failed loads, timeouts, and cache hits are not billed. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo documentation for options such as PNG, JPEG, WebP, PDF, full-page capture, CSS selectors, custom JavaScript, waits, headers, cookies, device presets, and signed webhooks. The free plan includes 1,000 screenshots each month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Practical checklist

  • Read the instance from ITestResult.getInstance().
  • Check the invocation type before test-only casting.
  • Use getParameters() for data-provider arguments, not fields.
  • Register the listener once through XML or @Listeners.
  • Confirm skipped-callback behavior and API details for the TestNG version in use.
  • Keep callback code thread-safe and inexpensive.

Frequently Asked Questions

How do I get the test instance in beforeInvocation?

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

Can I access private test fields directly?

Not through ordinary Java access. Add a suitable accessor or interface; use reflection only when a genuinely generic listener requires it.

Does getInstance return the same object for every data-provider row?

It returns the object associated with that invocation. Do not assume one object across rows or parallel execution; inspect your TestNG instantiation and parallel settings.

Quick Recap

Bestseller No. 1
SaleBestseller No. 3
Logitech K120 Full Size Wired Keyboard USB Plug-and-Play Windows - Black
Logitech K120 Full Size Wired Keyboard USB Plug-and-Play Windows - Black
Plastic parts in K120 include 51% certified post-consumer recycled plastic*; Product carbon footprint: 4.02 kg CO2e
$12.34
SaleBestseller No. 5
Logitech K270 Full Size Wireless Keyboard for Windows - Black
Logitech K270 Full Size Wireless Keyboard for Windows - Black
Plastic parts in K270 include 38% certified post-consumer recycled plastic; Eight hot keys: For instant access to the Internet, e-mail, music volume and more
$21.48

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.