Home > Java > javaTutorial > How to Effectively Assert Exceptions in JUnit Tests?

How to Effectively Assert Exceptions in JUnit Tests?

Patricia Arquette
Release: 2024-12-20 07:51:12
Original
952 people have browsed it

How to Effectively Assert Exceptions in JUnit Tests?

Executing Exception Assertions in JUnit Tests

Asserting that a specific exception is thrown during code execution is a common test scenario in JUnit. To do this effectively, JUnit provides several methods that enhance readability and simplify the testing process.

JUnit 5 and 4.13 Assertions

In JUnit 5 and 4.13, the @Test annotation with the expected attribute can be used directly:

@Test
public void testIndexOutOfBoundsException() {
    ArrayList<Object> emptyList = new ArrayList<>();
    assertThrows(IndexOutOfBoundsException.class, () -> emptyList.get(0));
}
Copy after login

AssertJ and Google Truth Assertions

External assertion libraries like AssertJ and Google Truth offer additional methods for exception assertions:

AssertJ:

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

@Test
public void testIndexOutOfBoundsException() {
    ArrayList<Object> emptyList = new ArrayList<>();
    assertThatThrownBy(() -> emptyList.get(0))
        .isInstanceOf(IndexOutOfBoundsException.class);
}
Copy after login

Google Truth:

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

@Test
public void testIndexOutOfBoundsException() {
    ArrayList<Object> emptyList = new ArrayList<>();
    assertThatCode(() -> emptyList.get(0)).willThrow(IndexOutOfBoundsException.class);
}
Copy after login

JUnit Pre-4.13 Assertions (Deprecated)

For JUnit versions prior to 4.13, a more cumbersome approach was to manually check for the exception within a try-catch block:

@Test
public void testIndexOutOfBoundsException() {
    boolean thrown = false;
    ArrayList<Object> emptyList = new ArrayList<>();

    try {
        emptyList.get(0);  // Intentionally triggers an exception
    } catch (IndexOutOfBoundsException e) {
        thrown = true;
    }

    assertTrue(thrown);
}
Copy after login

This approach is deprecated and less idiomatic than the aforementioned methods. Refer to the [JUnit Test-FAQ](https://junit.org/junit4/faq.html) for more details.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template