How can I write a TestNG test to ensure an exception is thrown under a specific condition?

I want to create a TestNG test that fails if a particular exception is not thrown, without using an extra boolean variable. Is there a simple way to achieve this using TestNG assert throws?

Hey @MattD_Burch, just to update you, TestNG has a built-in way to expect exceptions. You can simply declare the exception type your test should throw:

import org.testng.annotations.Test;

public class MyTest {

    @Test(expectedExceptions = IllegalArgumentException.class)
    public void testThrowsException() {
        // This should throw IllegalArgumentException
        myMethodThatThrows();
    }
}

The test will automatically fail if the exception is not thrown. No boolean flags needed.

Agree with @netra.agarwal , however if you want more control or to inspect the exception, assertThrows works similarly to JUnit 5:

import org.testng.annotations.Test;
import static org.testng.Assert.assertThrows;

public class MyTest {

    @Test
    public void testExceptionThrown() {
        IllegalArgumentException thrown = assertThrows(
            IllegalArgumentException.class,
            () -> myMethodThatThrows(),
            "Expected IllegalArgumentException to be thrown"
        );

        // Optionally, assert details on the exception
        assert thrown.getMessage().contains("invalid input");
    }
}

This is nice if you want to validate the exception message or other properties.

If you’re using an older version of TestNG, you can still avoid a boolean by rethrowing on success:

import org.testng.annotations.Test;

public class MyTest {

    @Test
    public void testExceptionThrown() {
        try {
            myMethodThatThrows();
            throw new AssertionError("Expected IllegalArgumentException was not thrown");
        } catch (IllegalArgumentException e) {
            // Test passes
        }
    }
}

This method works everywhere and keeps it simple: if the exception occurs, the test passes; otherwise, it fails with a clear message.