It is sometimes necessary to test that a piece of code does not throw an exception or that an exception is caught in another code block, ensuring that the caller method does not encounter an exception. To test such a scenario, one must verify that no exception is thrown from the code under test. In this article, we cover how to assert that no exception is thrown in both the AssertJ library and JUnit 5.
Previously, we showed how to assert exceptions in AssertJ and compared its syntax with JUnit 5. In this article, we need to do the exact opposite.
To achieve that, let’s first write a small method called findBy(String username)
as follows:
public Optional<User> findBy(String username) {
try {
return Optional.of(findByUsername(username));
} catch (UserNotFoundException userNotFoundException) {
return Optional.empty();
}
}
In the above code, if the user exists, the method returns their details. Otherwise, it returns an empty optional. The method should not throw any exception under any circumstances.
To test that, we can write a test in AssertJ as follows:
import static org.assertj.core.api.Assertions.assertThatCode;
@Test
void shouldNotThrowExceptionWhenRetrievingUser() {
assertThatCode(() -> userRepository.findBy("test")).doesNotThrowAnyException();
}
The JUnit 5 of it is as follows:
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
@Test
void shouldNotThrowExceptionWhenRetrievingUser() {
assertDoesNotThrow(() -> userRepository.findBy("test"));
}
Conclusion
In this article, we covered how to assert that no exception is thrown in AssertJ and JUnit 5. This is necessary to ensure a piece of code or a method does not throw any unwanted exception. As always, the tutorial’s code is available on Geeky Hacker GitHub repository.
Inline/featured images credits
- Featured image generated by Microsoft Designer