Java Reference
In-Depth Information
In this case, we expect the method return value to be
true
, and we want to include a check in our
test to make sure that this is really the case. We can now make sure that the
Assert that
check-
box is checked, enter
true
in the dialog, and select the
Close
button.
Concept:
An
assertion
is
an expression that
states a condition
that we expect
to be true. If the
condition is false,
we say that the
assertion fails. This
indicates an error in
our program.
■
Add a second comment to your sales item. Make sure the comments are valid (they have
unique authors and the rating is valid). Assert that the result is true for the second comment
addition as well.
■
We now expect two comments to exist. To test that this is indeed the case, call the
getNum-
berOfComments
method and assert that the result is 2.
This is the final stage of the test. We then press the
End
button to stop the recording. At that
point, BlueJ adds source code to the
SalesItemTest
class for our new method,
testTwo-
Comments
, then compiles the class and clears the object bench. The resulting generated method
is shown in Code 7.2.
Code 7.2
An automatically gener-
ated test method
@
Test
public
void
testTwoComments()
{
SalesItem salesIte1 =
new
SalesItem(
"Java Book"
, 12345);
assertEquals(
true
,
salesIte1.addComment(
"James Duckling"
,
"Great book. ..."
, 4));
assertEquals(
true
, salesIte1.addComment(
"Fred", "Like it"
, 2));
assertEquals(2, salesIte1.getNumberOfComments());
}
As can be seen, the method contains statements that reproduce the actions made when recording
it: a
SalesItem
object is created, and the
addComment
and
getNumberOfComments
methods
are called. The call to
assertEquals
is what checks that the result returned by these methods
matches the expected value. You can also see a new construct,
@Test
, before the method. This
is an annotation that identifies this method as a test method.
The exercises below are provided so that you can try this process out for yourself. They include
an example to show what happens if the actual value does not match the expected value.
Exercise 7.15
Create a test to check that
addComment
returns
false
when a comment
from the same author already exists.
Exercise 7.16
Create a test that performs negative testing on the boundaries of the rating
range. That is, test the values 0 and 6 as a rating (the values just outside the legal range). We
expect these to return
false
, so assert
false
in the result dialog. You will notice that one of
these actually (incorrectly) returns
true
. This is the bug we uncovered earlier in manual test-
ing. Make sure that you assert
false
anyway. The assertion states the
expected
result, not
the
actual
result.
Exercise 7.17
Run all tests again. Explore how the
Test Result
dialog displays the failed
test. Select the failed test in the list. What options do you have available to explore the details
of the failed test?
Search WWH ::
Custom Search