Books / Fundamentals of Computer Science / Chapter 3
JUnit
Classes are the “parts” of an object-oriented program.
Testing makes sure that the parts work correctly.
If the individual classes don’t work correctly, the overall program is probably not going to work correctly. Therefore, it is very important to have a good set of tests for the classes in your program.
JUnit is a unit testing framework for Java programs. To use JUnit, you write test classes. A test class is designed to test one Java class. It contains one or more test methods. Each test method is designed to test one particular feature of the class being tested.
In this chapter
General structure of a JUnit test class
The test class’s fields (member variables) store references to objects (generally, instances of the class being tested). These fields and the objects they point to are called the test fixture.
A test class’s setUp method creates the test fixture objects. This method is called automatically before each test method is called. It must be marked with the @Before annotation.
The test methods call methods on the test fixture objects and check to see that the methods compute the correct result, typically by calling an assertion method. Assertion methods are methods defined by the JUnit framework specifically for checking that calls to methods in classes being tested compute the expected result. Each test method must be marked with the @Test annotation.
Ideally, a test method should focus on one particular method to be tested.
Kinds of JUnit assertion methods:
Most assertions in JUnit test classes will boil down to checking that the return value of a method call is equal to an expected value.
If an assertion is not satisfied, it causes the test method containing the assertion to fail. If all assertions in a test method are satisfied, the test method containing the assertion passes. The goal of testing using JUnit is that all assertions in all test methods should pass.
Eclipse has built-in support for running JUnit tests. To run a JUnit test class within eclipse, right-click on the test class, and choose Run As…→JUnit test. The result will be displayed in the JUnit window:
- Green bar: all of the test methods passed
- Red bar: at least one of the test methods failed
JUnit Example
As an example, let’s consider an improved version of our Point class:
Here’s a very simple JUnit class for testing the Point class. We’ll call the test class PointTest.
This is a very simple example, but it demonstrates the basic idea: for each method in the Point class, we want to have one or more test methods which check whether or not the method behaves correctly using some test input.
Note that there is one method in Point that we didn’t test - the print method. It is actually quite difficult to test methods that write output to System.out.