Search⌘ K
AI Features

Testing Exception Handling with Mockito

Understand how to use Mockito to create mocks that simulate exceptions, enabling you to test error handling paths in your Java code effectively. Learn to configure mocked methods to throw exceptions and assert the expected behavior of your system under test.

In this lesson, we’re going to look into a great use of stub objects, which is their role in testing error conditions.

Handling error conditions

As we create our code, we need to ensure that it handles error conditions well. Some error conditions are easy to test. An example might be a user input validator. To test that it handles the error caused by invalid data, we simply write a test that feeds it invalid data and then write an assertion to check it successfully reported the data was invalid. But what about the code that uses it? If our SUT is code that responds to an error condition raised by one of its collaborators, we need to test that error response. How we test it depends on the mechanism we chose to report that error. We might be using a ...