Driving error handling code with tests
In this section, we’re going to look into a great use of stub objects, which is their role in testing 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.
We may also have chosen to use Java exceptions to report this error. Exceptions are controversial. If misused, they can...