How can I use testng assertthrows to test for mandatory exceptions?
I want to write a TestNG test that ensures an exception is thrown under specific conditions using testng assertthrows.
The test should fail automatically if the exception does not occur, without needing extra boolean checks. How can I achieve this properly?
In TestNG 7+, you can use Assert.assertThrows to verify an exception is thrown without extra flags. For example:
import org.testng.Assert;
import org.testng.annotations.Test;
@Test
public void testException() {
IllegalArgumentException thrown = Assert.assertThrows(
IllegalArgumentException.class,
() -> {
throw new IllegalArgumentException("Invalid input");
}
);
Assert.assertEquals(thrown.getMessage(), "Invalid input");
}
This fails automatically if the lambda does not throw the expected exception. I use this pattern whenever I need clean, concise exception tests.
Sometimes you want to inspect the exception in addition to checking that it’s thrown:
@Test
public void testMandatoryException() {
Exception ex = Assert.assertThrows(
Exception.class,
() -> someMethodThatMustThrow()
);
Assert.assertTrue(ex.getMessage().contains("must throw"));
}
This avoids extra boolean checks and gives more meaningful test failure messages. I often combine assertThrows with message validation for more robust tests.
If the method you want to test is already defined, you can pass a method reference to assertThrows:
@Test
public void testExceptionMethodReference() {
Assert.assertThrows(
IllegalStateException.class,
this::methodThatShouldThrow
);
}
private void methodThatShouldThrow() {
throw new IllegalStateException("Something went wrong");
}
This keeps your test concise and readable, while TestNG ensures the test fails if the exception doesn’t occur.