Assert exceptions in AssertJ

Assert exception in AssertJ

Besides JUnit, AssertJ is another popular testing framework for Java that provides a fluent API for writing clear and concise test assertions. It improves the readability of test code and provides comprehensive support for Java objects and collections. One of the areas in which AssertJ shines is the exception assertion. In this article, we cover how to assert exceptions in AssertJ.

To give a better understanding of how AssertJ makes tests more readable, we start with a simple example method that throws an exception. Then, we write tests in both JUnit and AssertJ. That should provide you with better clarity about the power of AssertJ.

Assume that we have a method, findByUsername(String username), that finds a user. If a user doesn’t exist, the method throws the UserNotFoundException exception as follows,

public User findByUsername(String username) throws UserNotFoundException {
    if (!"test".equalsIgnoreCase(username)) {
        throw new UserNotFoundException("Cannot find username: %s".formatted(username));
    }
    return new User("test", "first name", "last name");
}

To test the above method for the exception scenario, one can write a test with JUnit 5 (Jupiter) using the assertThrows() as follows,

@Test
void shouldThrowUserNotFoundException() {
    assertThrows(UserNotFoundException.class, () -> userRepository.findByUsername("nonExistenceUsername"));
}

To write the exact verification in AssertJ, we can use the assertThatThrownBy() as follows,

@Test
void shouldThrowUserNotFoundException() {
    assertThatThrownBy(() -> userRepository.findByUsername("nonExistenceUsername"));
}

We can even verify the exception message:

@Test
void shouldThrowUserNotFoundException() {
    assertThatThrownBy(() -> userRepository.findByUsername("nonExistenceUsername"))
        .isInstanceOf(UserNotFoundException.class)
        .hasMessage("Cannot find username: nonExistenceUsername");
}

Conclusion

In this article, we discussed how to assert exceptions in AssertJ. We started at first by writing a simple method that looks up a user by its username. Then we demonstrated how to verify for the exception using JUnit 5 assertThrows and then with AssertJ assertThatThrownBy to give a better perspective on how AssertJ exception assertion works. As always, the tutorial’s code is available on Geeky Hacker GitHub repository.

Inline/featured images credits