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@Testannotation.
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 arestatic,final, and written in all capitals, separating multiple words with underscoresLIKE_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.
