Introducing JUnit

The basic idea of writing a JUnit test is that statements from our main method such as

    System.out.println(b.isDribbleable());
    System.out.println("Expected: false");
are replaced with a special method call known as an assertion.
    assertEquals(false, b.isDribbleable());
The way it works is that the two arguments to the assertEquals method are the expected and actual values we are testing. If the expected and actual values don't match, the JUnit framework produces some output indicating what failed. If the test is successful, no output is produced. That makes it easy to pinpoint where the errors are.

There are many forms of assertions in the JUnit libraries, but the most common are various forms of assertEquals(expected, actual) like the one above.

A JUnit test, with four test cases corresponding to our four println statements, might look like this:


public class BasketballTests
{
    // margin of error for floating-point comparisons
    private static final double EPSILON = 10e-07;
    
    @Test
    public void testInitial()
    {
      Basketball b = new Basketball(5);
      assertEquals(false, b.isDribbleable());
    }

    @Test
    public void testInitialDiameter()
    {
      Basketball b = new Basketball(5);
      assertEquals(5.0, b.getDiameter(), EPSILON);
    }

    @Test
    public void testInflate()
    {
      Basketball b = new Basketball(5);
      b.inflate();
      assertEquals(true, b.isDribbleable());
    }

    @Test
    public void testDiameterAfterInflation()
    {
      Basketball b = new Basketball(5);
      b.inflate();
      assertEquals(5.0, b.getDiameter(), EPSILON);
    }
   
  }

You can see that a JUnit test is an ordinary Java class. Each test case is just a public void method that has no arguments. To tell the JUnit framework that the method should be used as a test case, we use the @Test annotation.

In the code above you can also see another variation of the assertEquals method. In testing the value of the diameter, two double values are being compared. Since floating-point arithmetic is not exact, we provide a margin of error, here using a constant called EPSILON (defined as 10 to the -7) that is provided as a third argument to assertEquals.