Home > Java > javaTutorial > How Can I Efficiently Assert Exceptions in JUnit Tests?

How Can I Efficiently Assert Exceptions in JUnit Tests?

DDD
Release: 2024-12-26 22:49:10
Original
207 people have browsed it

How Can I Efficiently Assert Exceptions in JUnit Tests?

Asserting Exceptions in JUnit Tests

Traditionally, testing for exceptions in JUnit involved verbose try-catch blocks as exemplified in the provided code. However, several alternatives exist that streamline this process.

JUnit 5 and 4.13

Since JUnit 4.13, the @Test(expected = IndexOutOfBoundsException.class) annotation can be used to assert that a specific exception is thrown during the execution of the annotated method. For example:

@Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {

    ArrayList emptyList = new ArrayList();
    Object o = emptyList.get(0);

}
Copy after login

AssertJ and Google Truth

AssertJ and Google Truth are popular assertion libraries that provide more readable and expressive assertions, including ones for testing exceptions. For instance, with AssertJ:

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

@Test
public void testIndexOfBoundsException() {

    ArrayList emptyList = new ArrayList();
    assertThatThrownBy(() -> emptyList.get(0)).isInstanceOf(IndexOutOfBoundsException.class);

}
Copy after login

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

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template