From the course: Complete Guide To Java Testing with JUnit 5 & Mockito

Unlock the full course today

Join today to access over 24,900 courses taught by industry experts.

Test exception handling with Mockito

Test exception handling with Mockito

- [Instructor] Whether it's a network failure, database connection issue, or unexpected input, properly handling exceptions is essential to preventing application crashes and providing users with meaningful feedback. With Mockito, we can verify our service works as expected, even if our dependencies do not. Let's take a look at an example. Here, we have a DatabaseServiceTest that depends on a database connection. We have an assertion statement from JUnit that allows us to assert the exception we want to be thrown. To ensure our dependency throws an error, we'll need to mock our dependency to return that exception. If we do not mock the method, then no exception will be thrown. The method will just return null because there's no stepping set for that method. Let's run this and see it in action. The expected exception was not thrown. If you see this when you're testing, it likely means you forgot to mock something or you're mocking something that doesn't need to be mocked. To fix this…

Contents