Java Reference
In-Depth Information
public
Response process(Request request)
throws
Exception
{
throw
new
Exception("error processing request");
}
}
}
This leaves creating a test method that registers the handler and tries processing a
request—for example, like the one shown in listing 3.12.
Listing 3.12
testProcessRequestAnswersErrorResponse
, first iteration
public
class
TestDefaultController
{
[...]
@Test
public
void
testProcessRequestAnswersErrorResponse()
{
SampleRequest request =
new
SampleRequest();
SampleExceptionHandler handler =
new
SampleExceptionHandler();
controller.addHandler(request, handler);
Response response = controller.processRequest(request);
Create request
and handler
objects
Reuse controller
object from
listing 3.8
assertNotNull("Must not return a null response", response);
assertEquals(ErrorResponse.class, response.getClass());
}
}
Test the
outcome
If you ran this test through
JU
nit, it would fail! A quick look at the message tells
you two things. First, you need to use a different name for the test request, because
there's already a request named
Test
in the fixture. Second, you may need to add
more exception handling to the class so that a
RuntimeException
isn't thrown
in production.
As to the first item, you can try using the request object in the fixture instead of
your own, but that fails with the same error. (Moral: Once you have a test, use it to
explore alternative coding strategies.) You could consider changing the fixture. If you
remove from the fixture the code that registers a default
SampleRequest
and
Sample-
Handler
, you introduce duplication into the other test methods—not good. Better to
fix the
SampleRequest
so it can be instantiated under different names. Listing 3.13 is
the refactored result (changes from listings 3.11 and 3.12 are in bold).
Listing 3.13
testProcessRequestExceptionHandler
, fixed and refactored
public class TestDefaultController
{
[...]
private class SampleRequest implements Request
{
private static final String DEFAULT_NAME = "Test";
private String name;
B