Home >Java >javaTutorial >How Can I Effectively Test for Exception Handling in JUnit?

How Can I Effectively Test for Exception Handling in JUnit?

DDD
DDDOriginal
2024-12-20 05:49:10572browse

How Can I Effectively Test for Exception Handling in JUnit?

Testing Exception Handling in JUnit

In JUnit, testing whether a specific exception is thrown can be achieved in multiple ways.

JUnit 5 and 4.13

The @Test annotation now supports the expected attribute, which allows you to specify the expected exception type:

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

AssertJ or Google Truth

Third-party assertion libraries like AssertJ and Google Truth provide more concise syntax for exception testing:

// AssertJ
assertThatThrownBy(() -> foo.doStuff()).isInstanceOf(IndexOutOfBoundsException.class);

// Google Truth
assertWithMessage("Expected IndexOutOfBoundsException").thatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> foo.doStuff());

JUnit <= 4.12

For JUnit 4.12 and earlier, there are several options:

  1. Boolean flag: Similar to the code in the original question.
  2. @Rule: The @Rule annotation can be used to create a test rule that asserts an exception is thrown.
  3. Custom matchers: Create a custom Hamcrest matcher to check if an exception of a specific type was thrown.

Refer to the JUnit Test-FAQ for more details on these options.

The above is the detailed content of How Can I Effectively Test for Exception Handling in JUnit?. 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