Unit Testing With println
Testing is a discipline in itself. (At some point you may find yourself taking Com S 417, Software Testing.) Determining whether a complex system is going to work correctly under all conditions is extremely difficult. In this course we will only focus on unit testing, which is where we test
a single component (usually a class) all by itself to ensure that it conforms to its specification.
We have seen many examples of simple unit tests. As one example, consider the class Basketball
.
We saw this class back in lab 2; you can review the
javadoc here.
In order to test it, we start thinking about what should be true about
a correctly implemented basketball:
- A newly constructed basketball is not dribbleable
- A newly constructed basketball should have the diameter it was constructed with
- After inflating, the basketball should be dribbleable
- After inflating, the basketball should still have the diameter it was constructed with
public class BasketballExample { public static void main(String[] args) { Basketball b = new Basketball(5); // A newly constructed basketball should not be dribbleable System.out.println(b.isDribbleable()); System.out.println("Expected: false"); // A newly constructed basketball should have the diameter it was constructed with System.out.println(b.getDiameter()); System.out.println("Expected: 5.0"); // After inflating, the basketball should be dribbleable b.inflate(); System.out.println(b.isDribbleable()); System.out.println("Expected: true"); // After inflating, the basketball should still have the diameter it was constructed with System.out.println(b.getDiameter()); System.out.println("Expected: 5.0"); } }If the
Basketball
class is implemented correctly, running this main
method
should produce the output:
false Expected: false 5.0 Expected: 5.0 true Expected: true 5.0 Expected: 5.0
Using a test framework
With only four test cases, it is easy enough to look at the output and see whether the actual values match the expected values. TheBasketball
class is very simple. A more complex class may have dozens or hundreds
of test cases, and it is tedious to have to read through the output to check for correct values.
Since we are programmers, we wonder: couldn't we just write a program to automatically
check the test output? And (since we are programmers) of course the answer
is yes! That is the idea of a test framework. Instead of using
System.out.println
, we write the test using a few special methods
defined by the framework,
and the framework completely automates the process of checking the
results. In this course we use a framework called JUnit that extremely easy
to use and is nicely integrated with Eclipse.