There are lots of different strategies for testing, and lots of different available to help with testing. For example, in Java, one of the most common tools is junit. Here, we are going to describe a strategy which doesn't involve any tools, just Java's assertion feature, which was mentioned in the calculation chapter. Here's an example program:
You run the program with java -ea Calculator to say that you want
to test the program rather than run it normally. The -ea flag means
enable assertions, which are lines starting with the assert
keyword.
The line assert test(); runs the test method before running the
program normally, if assertions are enabled. The test method
contains individual tests of the sum method. The sum
method is slightly different from before - it now returns a string rather than
printing it. This makes testing easier (and is also a better design).
In the sum function, there are assertions at the beginning which check that
the arguments are correct. These come into play when the program is run
normally, after the tests, to catch cases where the method might be called with
bad arguments. These can safely be left in the code permanently. They are not
executed (and cause no inefficiency) when the program is run without the
-ea flag.
The assert keyword can be used in three ways:
assert boolean expression; assert boolean expression : message string; assert equal(expression, result);
The third form is an abbreviation which saves you having to write something like this, where you have to repeat a long expression:
assert expression == result : "Got " + expression + ", expecting " + result;
The equal method is one you write yourself which compares two
things. If they are equal, it returns true and if not, it prints
a suitable message like the one above and then prints false:
boolean equal(Object x, Object y)
{
if (x.equals(y)) return true;
System.out.println("Got " + x + ", expecting " + y);
return false;
}