Skip to main content

Section 8.4 A simple unit test

Let’s practice writing tests by testing the Grade class. Tests typically go in separate files, under a tests directory whose structure mirrors that of your source directory. In there we’ll create a GradeTest class. It is customary to name test classes that way, based on the class they are testing with the word Test appended. So here is a start:
import org.junit.Test;
import static org.junit.Assert.*;

public class GradeTest {
  @Test
  public void letterGradesHaveAppropriatePoints() {
    // ...
  }
}
I like to use JUnit 4 myself, so the syntax you see will be following that format. We are importing the assertion library, so we can simply write assertEquals(...) rather than a longer version, and we also import the @Test annotation from org.junit. I named my test to indicate what I expect to be happening.
JUnit 4 tests must be public void methods in public classes, annotated with the @Test annotation.
Now I will work on the content of my test. I will start with the arrange part: I need to create a suitable Grade object.
public void letterGradesHaveAppropriatePoints() {
  Grade grade = new Grade("A");
  // ...
}
Next I need to act on that grade, by calling the method I want to test and storing the result:
public void letterGradesHaveAppropriatePoints() {
  Grade grade = new Grade("A");
  double points = grade.getPoints();
  // ...
}
Finally, I must check that I get the expected result:
public void letterGradesHaveAppropriatePoints() {
  Grade grade = new Grade("A");
  double points = grade.getPoints();
  assertEquals(4.00, points, 0.00000001);
}
Note the 0.00000001 there. When comparing doubles, JUnit requires you to specify the precision that you expect. It will treat the two numbers as equal as long as their difference doesn’t exceed this so-called delta value. I don’t particularly like seeing it there, and I certainly don’t want to be typing it every time. I will therefore perform a Extract Constant refactoring, and turn that number into a constant called DELTA.
Customarily constant fields are static, final, and written in all capitals, separating multiple words with underscores LIKE_SO.
So that’s the basics of writing unit tests: Bring your system to the state you want to test, act on that system, and verify the results.