Home >Java >javaTutorial >How Do I Assert Exception Handling in JUnit Tests?

How Do I Assert Exception Handling in JUnit Tests?

Susan Sarandon
Susan SarandonOriginal
2025-01-04 07:54:35473browse

How Do I Assert Exception Handling in JUnit Tests?

Asserting Exception Handling in JUnit Tests

In JUnit, testing code that should throw an exception requires a clean and concise approach. While manually checking for exceptions is possible, it's not the idiomatic way.

JUnit 5 and 4.13

In JUnit versions 5 and 4.13, you can use @Test(expected = ExceptionClass.class) annotation on the test method. This expects the specified exception to be thrown.

Example:

@Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {
    ArrayList emptyList = new ArrayList();
    emptyList.get(0);
}

AssertJ and Google-Truth

If using libraries like AssertJ or Google-Truth, you can employ their assertions for validating exceptions.

AssertJ:

import static org.assertj.core.api.Assertions.assertThatThrownBy;

@Test
public void testFooThrowsIndexOutOfBoundsException() {
    assertThatThrownBy(() -> foo.doStuff()).isInstanceOf(IndexOutOfBoundsException.class);
}

Google-Truth:

import static com.google.common.truth.Truth.assertThat;

@Test
public void testFooThrowsIndexOutOfBoundsException() {
    assertThat(assertThrows(IndexOutOfBoundsException.class, foo::doStuff)).isNotNull();
}

JUnit <= 4.12

In JUnit versions less than or equal to 4.12, you can use Rule or TryCatch to handle exceptions.

Using Rule:

@Rule
public ExpectedException thrown = ExpectedException.none();

@Test
public void testIndexOutOfBoundsException() {
    thrown.expect(IndexOutOfBoundsException.class);
    ArrayList emptyList = new ArrayList();
    emptyList.get(0);
}

Using TryCatch:

import static org.junit.Assert.assertEquals;

@Test
public void testIndexOutOfBoundsException() {
    try {
        ArrayList emptyList = new ArrayList();
        emptyList.get(0);
        fail("IndexOutOfBoundsException was expected");
    } catch (IndexOutOfBoundsException e) {
        assertEquals(e.getClass(), IndexOutOfBoundsException.class);
    }
}

The above is the detailed content of How Do I Assert Exception Handling in JUnit Tests?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn