Testing Exception Handling with Mockito

Learn about testing exception handling with Mockito in Java.

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 may be using a simple status code, in which case returning that error code from a stub will work very well.

Get hands-on with 1200+ tech skills courses.