Java Reference
In-Depth Information
Exercise 7.18
Create a test class that has
Comment
as its reference class. Create a test
that checks whether the author and rating details are stored correctly after creation. Record
separate tests that check whether the
upvote
and
downvote
methods work as expected.
Exercise 7.19
Create tests for
SalesItem
that test whether the
findMostHelpfulCom-
ment
method works as expected. Note that this method returns a
Comment
object. During
your testing, you can use the
Get
button in the method result dialog to get the result object
onto the object bench, which then allows you to make further method calls and add assertions
for this object. This allows you to identify the comment object returned (e.g., by checking its
author). You can also assert that the result is
null
or
not null
, depending on what you expect.
7.4.4
Fixtures
As a set of test methods is built up, it is common to find yourself creating similar objects for
each one. For instance, every test of the
SalesItem
class will involve creating at least one
SalesItem
and initializing it, often by adding one or more comments. An object or a group
of objects that is used in more than one test is known as a
fixture.
Two menu items associated
with a test class enable us to work with fixtures in BlueJ:
Object Bench to Test Fixture
and
Test
Fixture to Object Bench.
In your project, create two
SalesItem
objects on the object bench.
Leave one without any comments, and add two comments to the other. Now select
Object
Bench to Test Fixture
from
SalesItemTest
. The objects will disappear from the object bench,
and if you examine the source code of
SalesItemTest
, you will see that its
setUp
method
looks something like Code 7.3, where
salesIte1
and
salesIte2
have been defined as fields.
Concept:
A
fixture
is a set of
objects in a defined
state that serves
as a basis for unit
tests.
Code 7.3
Creating a fixture
/**
* Sets up the test fixture.
*
* Called before every test case method.
*/
@
Before
public
void
setUp()
{
salesIte1 =
new
SalesItem(
"Java Book"
,
12345);
salesIte2 =
new
SalesItem(
"Other"
, 123);
salesIte2.addComment(
"Fred"
,
"too expensive"
, 1);
}
The significance of the
setUp
method is that it is automatically called immediately before
every test method is called. (The
@Before
annotation above the method header ensures this.)
This means that the individual test methods no longer need to create their own versions of the
fixture objects.
Once we have a fixture associated with a test class, recording tests becomes significantly simpler.
Whenever we create a new test method, the objects from the fixture will automatically appear on
the object bench—there is no longer a need to create new test objects manually each time.
Search WWH ::
Custom Search