Java Reference
In-Depth Information
work when we ship the rest of the application or whenever we make a subsequent
modification. If we put these requirements together, we come up with the idea of writ-
ing a simple test program for the add method.
The test program could pass known values to the method and see if the result
matches our expectations. We could also run the program again later to be sure
the method continues to work as the application grows. What's the simplest possi-
ble test program we could write? What about the CalculatorTest program shown
in listing 1.2?
Listing 1.2
A simple test calculator program
public class CalculatorTest {
public static void main(String[] args) {
Calculator calculator = new Calculator();
double result = calculator.add(10,50);
if (result != 60) {
System.out.println("Bad result: " + result);
}
}
}
The first CalculatorTest is simple indeed. It creates an instance of Calculator ,
passes it two numbers, and checks the result. If the result doesn't meet our expecta-
tions, we print a message on standard output.
If we compile and run this program now, the test will quietly pass, and all will seem
well. But what happens if we change the code so that it fails? We'll have to watch the
screen carefully for the error message. We may not have to supply the input, but we're
still testing our own ability to monitor the program's output. We want to test the code,
not ourselves!
The conventional way to signal error conditions in Java is to throw an exception.
Let's throw an exception instead to indicate a test failure.
Meanwhile, we may also want to run tests for other Calculator methods that we
haven't written yet, like subtract or multiply . Moving to a modular design would
make it easier to catch and handle exceptions as well as extend the test program later.
Listing 1.3 shows a slightly better CalculatorTest program.
Listing 1.3
A (slightly) better test calculator program
public class CalculatorTest {
private int nbErrors = 0;
public void testAdd() {
Calculator calculator = new Calculator();
double result = calculator.add(10, 50);
if (result != 60) {
throw new IllegalStateException("Bad result: " + result);
}
}
B
 
 
 
Search WWH ::




Custom Search