Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^252) | File Objects and Looping Statements


5.4 Testing and Debugging


Loop-Testing Strategy


Even if a loop has been properly designed, it is still important to test it rigorously, because
the chance of an error creeping in during the implementation phase is always present. To
test a loop thoroughly, we must check for the proper execution of both a single iteration
and multiple iterations.
Remember that a loop has seven parts (corresponding to the seven questions in our
checklist). A test strategy must test each part. Although all seven parts aren’t implemented
separately in every loop, the checklist reminds us that some loop operations serve multi-
ple purposes, each of which should be tested. For example, the incrementing statement in
a count-controlled loop may update both the process and the ending condition. It’s impor-
tant to verify that it performs both actions properly with respect to the rest of the loop.
Consider what the acceptable ranges of variables are and what sorts of I/O opera-
tions you expect see in the loop. Try to devise data sets that could cause the variables to
go out of range or leave the files in unexpected states.
It’s also good practice to test a loop for four special cases:

1.When the loop is skipped entirely
2.When the loop body is executed just once
3.When the loop executes some normal number of times
4.When the loop fails to exit

Statements following a loop often depend on its processing. If a loop can be skipped,
those statements may not execute correctly. If it’s possible to execute a single iteration of a
loop, the results can show whether the body performs correctly in the absence of the effects
of previous iterations, which can prove very helpful when you’re trying to isolate the source
of an error. Obviously, it’s important to test a loop under normal conditions, with a wide va-
riety of inputs. If possible, you should test it with real data in addition to mock data sets.
Count-controlled loops should be tested to confirm that they execute exactly the right num-
ber of times. Finally, if there is any chance that a loop might never exit, your test data should
try to make that happen.
Testing an application can be as challenging as writing it. To test an application, you
need to step back, take a fresh look at what you’ve written, and then attack it in every way
possible to make it fail. This isn’t always easy to do, but it’s necessary to make your ap-
plications be reliable. (A reliable applicationworks consistently and without errors regard-
less of whether the input data is valid or invalid.)

Test Plans Involving Loops


In Chapter 4, we introduced formal test plans and discussed the testing of branches.
Those guidelines still apply to applications with loops, but here we provide some additional
Free download pdf