Java Reference
In-Depth Information
Although it's simple, this unit test confirms the key premise that the mechanism for
storing and retrieving
RequestHandler
is alive and well. If
addHandler
or
getRequest
fails in the future, the test will quickly detect the problem.
As you create more tests like this, you'll notice that you follow a pattern:
Set up the test by placing the environment in a known state (create objects,
acquire resources). The pretest state is referred to as the
test fixture
.
1
Invoke the method under test.
2
Confirm the result, usually by calling one or more assert methods.
3
3.2.3
Processing a request
Let's look at testing the core purpose of the controller, processing a request. Because
you know the routine, we present the test in listing 3.7 and review it.
Listing 3.7
testProcessRequest
method
import static org.junit.Assert.*;
public
class
TestDefaultController
{
[...]
@Test
public
void
testProcessRequest()
{
Request request =
new
SampleRequest();
RequestHandler handler =
new
SampleHandler();
controller.addHandler(request, handler);
Response response = controller.processRequest(request);
assertNotNull("Must not return a null response", response);
assertEquals(“Response should be of type SampleResponse”,
SampleResponse.class, response.getClass());
B
C
E
D
F
}
}
First, annotate the test with the
@Test
annotation and give the test a simple, uniform
name
B
. Set up the test objects and add the test handler
C
.
At
D
the code diverges from listing 3.6 and calls the
processRequest
method. You
verify that the returned
Response
object isn't
null
E
. This is important because you
call the
getClass
method on the
Response
object. It will fail with a dreaded
Null-
PointerException
if the
Response
object is
null
. You use the
assertNotNull(String,
Object)
signature so that if the test fails, the error displayed is meaningful and easy to
understand. If you'd used the
assertNotNull(Object)
signature, the
JU
nit runner
would have displayed a stack trace showing a
java.lang.AssertionError
exception
with no message, which would be more difficult to diagnose.
Once again, compare the result of the test against the expected
SampleResponse
class
F
.