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
From the course: Complete Guide To Java Testing with JUnit 5 & 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
-
-
-
-
-
-
-
-
-
(Locked)
Spy on real objects with Mockito4m 31s
-
(Locked)
Test exception handling with Mockito2m 10s
-
(Locked)
Test void methods with Mockito5m 10s
-
(Locked)
Verify no (or a set number of) interactions5m 1s
-
(Locked)
GetAllValues with ArgumentCaptor5m 1s
-
(Locked)
Test asynchronous code with Mockito3m 17s
-
(Locked)
Mock a static method with Mockito3m 15s
-
(Locked)
Challenge: Test an ordering service1m 2s
-
(Locked)
Solution: Test an ordering service8m 21s
-
(Locked)
-
-