Java Reference
In-Depth Information
JUnit best practices: unit test one object at a time
A vital aspect of unit tests is that they're finely grained. A unit test independently
examines each object you create, so that you can isolate problems as soon as they
occur. If you put more than one object under test, you can't predict how the objects
will interact when changes occur to one or the other. When an object interacts
with other complex objects, you can surround the object under test with predict-
able test objects. Another form of software test, integration testing, examines how
working objects interact with each other. See chapter 4 for more about other types
of tests.
W
HERE
DO
TEST
CLASSES
LIVE
?
Where do you put the test classes? Java provides several alternatives. For starters, you
could do one of the following:
Make them public classes in your package.
■
Make them inner classes within your test-case class.
■
If the classes are simple and likely to stay that way, then it's easiest to code them as
inner classes. The classes in this example are simple. Listing 3.5 shows the inner
classes you can add to the
TestDefaultController
class.
Listing 3.5
Test classes as inner classes
public
class
TestDefaultController
{
[...]
private
class
SampleRequest
implements
Request
{
public
String
getName()
{
return
"Test";
}
}
private
class
SampleHandler
implements
RequestHandler
{
public
Response process(Request request)
throws
Exception
{
return
new
SampleResponse();
}
}
private
class
SampleResponse
implements
Response
{
// empty
}
[...]
B
C
D
First, set up a request object
B
that returns a known name (
Test
). Next, imple-
ment a
SampleHandler
C
. The interface calls for a
process
method, so you have to