How can I use **JUnit expected exception** to assert that a specific exception is thrown in my tests?

How can I assert that a specific exception is thrown in JUnit tests?

I want to test that some code throws an exception in JUnit in an idiomatic way. While I can use a try-catch block like this:

@Test
public void testFooThrowsIndexOutOfBoundsException() {

    boolean thrown = false;

    try {
        foo.doStuff();
    } catch (IndexOutOfBoundsException e) {
        thrown = true;
    }

    assertTrue(thrown);
}

I recall that there is an annotation or an Assert.xyz method to handle expected exceptions in a cleaner, more JUnit-idiomatic way.

How can I use JUnit expected exception to assert that a specific exception is thrown in my tests?

I think you are slightly using the exception wrong here , let me help you fix your query:

You can try using the @Test(expected = Exception.class)Annotation. The most straightforward way to assert that an exception is thrown in JUnit is to use the@Test` annotation with the expected attribute.

This allows you to specify the exception type that you expect to be thrown during the test. If the exception is thrown, the test passes; otherwise, it fails.

@Test(expected = IndexOutOfBoundsException.class)
public void testFooThrowsIndexOutOfBoundsException() {
    foo.doStuff();  // This should throw IndexOutOfBoundsException
}

Hope it is helpful :slight_smile:

Hey

Just to add up to @joe-elmoufak

You can also use Assert.assertThrows() with JUnit.

In JUnit 5, you can use Assertions.assertThrows() to assert that a specific exception is thrown. This method is a more flexible and modern approach to exception testing, and it provides the ability to capture the exception and inspect it if needed.

@Test
public void testFooThrowsIndexOutOfBoundsException() {
    IndexOutOfBoundsException exception = assertThrows(IndexOutOfBoundsException.class, () -> {
        foo.doStuff();
    });
    // Optionally assert more about the exception here
}

You can try using this solution as well.

Using try-catch with assertTrue (Manual Assertion): This is the approach you’re familiar with but is less idiomatic for modern JUnit testing.

You can catch the exception in a try-catch block and then assert that it was thrown using assertTrue or another assertion method.

However, this is typically more verbose than the built-in JUnit approaches.

@Test
public void testFooThrowsIndexOutOfBoundsException() {
    boolean thrown = false;
    try {
        foo.doStuff();
    } catch (IndexOutOfBoundsException e) {
        thrown = true;
    }
    assertTrue(thrown);
}