Java Reference
In-Depth Information
1.2
Starting from scratch
For our first example, we create a simple calculator class that adds two numbers. Our
calculator provides an API to clients and doesn't contain a user interface; it's shown in
listing 1.1.
Listing 1.1
The test calculator class
public class Calculator {
public double add( double number1, double number2) {
return number1 + number2;
}
}
Although the documentation isn't shown, the intended purpose of the Calculator 's
add(double, double) method is to take two doubles and return the sum as a double.
The compiler can tell us that it compiles, but we should also make sure it works at run-
time. A core tenet of unit testing is, “Any program feature without an automated test
doesn't exist.” 5 The add method represents a core feature of the calculator. We have
some code that allegedly implements the feature. What's missing is an automated test
that proves our implementation works.
Isn't the add method too simple to break?
The current implementation of the add method is too simple to break. If add
were a minor utility method, then we might not test it directly. In that case, if
add did fail, then tests of the methods that used add would fail. The add method
would be tested indirectly, but tested nonetheless. In the context of the calcula-
tor program, add isn't just a method; it's a program feature . In order to have con-
fidence in the program, most developers would expect there to be an automated
test for the add feature, no matter how simple the implementation appears. In
some cases, we can prove program features through automatic functional tests
or automatic acceptance tests. For more about software tests in general, see
chapter 3.
Testing anything at this point seems problematic. We don't even have a user interface
with which to enter a pair of double s. We could write a small command-line program
that waited for us to type in two double values and then displayed the result. Then
we'd also be testing our own ability to type numbers and add the result ourselves. This
is much more than what we want to do. We want to know if this unit of work will add
two double s and return the correct sum. We don't want to test whether programmers
can type numbers!
Meanwhile, if we're going to go to the effort of testing our work, we should also try
to preserve that effort. It's good to know that the add(double,double) method
worked when we wrote it. But what we really want to know is whether the method will
5
Kent Beck, Extreme Programming Explained: Embrace Change (Reading, MA: Addison-Wesley, 1999).
 
 
 
 
 
 
 
 
 
Search WWH ::




Custom Search