October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

How to Write Exception Tests in TestNG

Use TestNG’s expectedExceptions for method-wide checks and Assert.expectThrows when only one operation should throw or you need to inspect the exception.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use @Test(expectedExceptions = YourException.class) when the test method itself should throw the expected exception. If only one call should throw—or you need to inspect the exception—use TestNG’s scoped Assert.expectThrows instead.

Expect an exception from the whole test method

Annotate the test with the exception class your code is expected to throw:

import org.testng.annotations.Test;

@Test(expectedExceptions = IllegalArgumentException.class)
public void rejectsInvalidInput() {
    service.process(null);
}

TestNG passes this test if the method throws the expected exception. It fails if the method returns without throwing or if a different exception escapes. The annotation can accept multiple expected exception classes, but list more than one only when the contract genuinely permits each type. See the TestNG annotation documentation and the TestNG 7.11.0 @Test Javadoc.

Keep this form focused: the expected exception must escape the test method, so avoid unrelated operations that could throw the same type and accidentally satisfy the expectation.

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

Check the exception message

TestNG 7.11.0’s @Test annotation also provides expectedExceptionsMessageRegExp. It checks the exception message against a regular expression when expectedExceptions is configured:

@Test(
    expectedExceptions = IllegalArgumentException.class,
    expectedExceptionsMessageRegExp = ".*must not be null.*"
)
public void rejectsNullInput() {
    service.process(null);
}

The documented default pattern is .*, which does not meaningfully constrain the message. Supply a pattern that checks the text you care about. This is a regex match, not a plain substring assertion: escape regular-expression metacharacters if you need to match punctuation literally, and avoid depending on message details that can vary dynamically.

Scope the assertion to one operation

Use Assert.expectThrows when setup or other assertions should run normally and only one operation is expected to throw. It returns the exception, so you can inspect its message or other properties:

import org.testng.Assert;

IllegalArgumentException exception = Assert.expectThrows(
    IllegalArgumentException.class,
    () -> service.process(null)
);
Assert.assertTrue(exception.getMessage().contains("must not be null"));

The API reference for TestNG 7.9.0 says expectThrows runs a ThrowingRunnable, returns the exception of the expected type, and raises AssertionError if nothing is thrown or the wrong type is thrown. That Javadoc marks the method as available since TestNG 6.9.5. Verify that the version in your build includes it before using it; the reference is the TestNG 7.9.0 Assert Javadoc.

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

Choose the right form

Need Use Why
The test method itself should throw the expected type @Test(expectedExceptions = ...) Concise method-wide expectation.
Only a particular call should throw Assert.expectThrows(...) Limits the assertion to that operation.
You need to inspect the exception object Assert.expectThrows(...) Returns the caught expected exception for further assertions.
Your project cannot use expectThrows Try/catch with Assert.fail() Provides a scoped fallback using basic assertions.

The distinction is scope: an annotation applies to the entire test method, while expectThrows applies to the supplied runnable. TestNG’s book contents include a section on when not to use expectedExceptions; a community example also discusses multi-statement tests and inspecting exception criteria (TestNG documentation; community example).

Use try/catch when necessary

If your TestNG version or project constraints prevent use of expectThrows, explicitly fail when the call returns, then assert on the exception in the catch block:

try {
    service.process(null);
    Assert.fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException exception) {
    Assert.assertTrue(exception.getMessage().contains("must not be null"));
}

Keep the try block limited to the operation being tested. Otherwise, a different statement could throw the same type and make the test misleading.

Common mistakes and fixes

  • The expected exception is caught inside the test. If you use expectedExceptions, do not catch the exception and return normally; TestNG then sees no exception escaping the method and fails the expectation. Use expectThrows or try/catch with an explicit failure instead.
  • The test contains several operations. A matching exception from an unrelated operation can satisfy a method-wide expectation. Move the expected operation into a scoped expectThrows call.
  • The expected type is too broad. Prefer the specific exception promised by the method’s contract. A broad superclass can allow unintended failures to pass if its subtypes are also acceptable to the assertion.
  • The message pattern is too loose or malformed. Remember that expectedExceptionsMessageRegExp uses regex syntax. Use a pattern that constrains the intended text and escape literal regex punctuation.
  • An assertion failure is mistaken for the application exception. TestNG assertion failures fail the test; they do not demonstrate that the method under test threw the expected application exception.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

This TestNG guide does not require browser screenshots. If you do need to capture a page for a test report or debugging artifact, ScreenshotNeo offers a one-request screenshot API. See the ScreenshotNeo API documentation.

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.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo accepts cookie and consent banners and removes supported consent platforms, newsletter popups, and chat widgets before capture; those steps can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides screenshot and PDF tools for AI agents. The free plan includes 1,000 screenshots a month without a card; paid plans start at $5 for 3,000.

Sign up for ScreenshotNeo’s free plan.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.