Java Reference
In-Depth Information
(continued)
What about things like JavaBean getters and setters? Well, that depends. If you're
coding them by hand in a text editor, then yes, you might want to test them. It's
surprisingly easy to miscode a setter in a way that the compiler won't catch. But
if you're using an IDE that watches for such things, then your team might decide
not to test simple JavaBean properties.
We're all human, and often we tend to be sloppy when it comes to exception cases.
Even textbooks scrimp on error handling so as to simplify the examples. As a result,
many otherwise great programs aren't error proofed before they go into production.
If properly tested, an application should not expose a screen of death but should trap,
log, and explain all errors gracefully.
3.3.1
Simulating exceptional conditions
The exceptional test case is where unit tests shine. Unit tests can simulate exceptional
conditions as easily as normal conditions. Other types of tests, like functional and
acceptance tests, work at the production level. Whether these tests encounter systemic
errors is often a matter of happenstance. A unit test can produce exceptional condi-
tions on demand.
During our original fit of inspired coding, we had the foresight to code an error
handler into the base classes. As you saw back in listing 3.2, the processRequest
method traps all exceptions and passes back a special error response instead:
try
{
response = getHandler(request).process(request);
}
catch (Exception exception)
{
response = new ErrorResponse(request, exception);
}
How do you simulate an exception to test whether your error handler works? To test
handling a normal request, you created a SampleRequestHandler that returned a
SampleRequest (see listing 3.5). To test the handling of error conditions, you can
create a SampleExceptionHandler that throws an exception instead, as shown in list-
ing 3.11.
Listing 3.11
Request handler for exception cases
public class TestDefaultController
{
[...]
private class SampleExceptionHandler implements RequestHandler
{
 
 
 
 
Search WWH ::




Custom Search