Java Reference
In-Depth Information
code that too. You're not testing the
process
method right now, so you have it
return a
SampleResponse
object to satisfy the signature. Go ahead and define an
empty
SampleResponse
D
so you have something to instantiate.
With the scaffolding from listing 3.5 in place, let's look at listing 3.6, which shows
the test for adding a
RequestHandler
.
Listing 3.6
TestDefaultController.testAddHandler
[...]
import static org.junit.Assert.*;
public
class
TestDefaultController
{
[...]
@Test
public
void
testAddHandler()
{
Request request =
new
SampleRequest();
RequestHandler handler =
new
SampleHandler();
controller.addHandler(request, handler);
RequestHandler handler2 = controller.getHandler(request);
assertSame("Handler we set in controller should be the
same handler we get", handler2, handler);
}
}
B
C
D
E
F
Pick an obvious name for the test method, and annotate your test method with the
@Test
annotation
B
. Remember to instantiate your test objects
C
. This code gets to
the point of the test:
controller
(the object under test) adds the test handler
D
.
Note that the
DefaultController
object is instantiated by the
@Before
annotated
method (see listing 3.4).
Read back the handler under a new variable name
E
, and check to see if you get
back the same object you put in
F
.
JUnit best practices: choose meaningful test method names
You can see that a method is a test method by the
@Test
annotation. You also
must be able to understand what a method is testing by reading the name.
Although JUnit doesn't require any special rules for naming your test methods, a
good rule is to start with the
test
XXX
naming scheme, where
XXX
is the name of
the domain method to test. As you add other tests against the same method, move
to the
test
XXXYYY
scheme, where
YYY
describes how the tests differ. Don't be
afraid that the names of your tests are getting long or verbose. As you'll see by the
end of the chapter, it's sometimes not so obvious what a method is testing by look-
ing at its
assert
methods. Name your test methods in a descriptive fashion, and
add comments where necessary.