What should you know about JUnit to work effectively in a Java codebase?
There are five or six things that you need to know, and they are not many.
The first thing is the shape of a test class. The annotation @Test marks a method as a test, and the assertions are the methods assertEquals, assertTrue, assertNull, assertSame and assertThrows. The methods that set up and tear down are marked with @BeforeEach and @AfterEach.
public class Main {
public static void main(String[] args) {
// The shape of a JUnit 5 test class, shown without the library.
Calculator calculator = new Calculator();
check("two and two", 4, calculator.add(2, 2));
check("minus one and one", 0, calculator.add(-1, 1));
check("the empty total", 0, calculator.total());
}
static void check(String name, int expected, int actual) {
if (expected != actual) {
System.out.println("FAILED " + name + " : expected " + expected + " but got " + actual);
return;
}
System.out.println("passed " + name);
}
}
class Calculator {
private int total;
int add(int first, int second) {
this.total = this.total + first + second;
return this.total;
}
int total() {
return this.total;
}
}
The second thing is that a test class and its test methods do not have to be public. In JUnit 5 they are usually package private, and that is the style that the library expects.
The third thing is the annotation @DisplayName, which gives a test a name that a person can read, and the annotation @Nested, which groups related tests inside one class.
The fourth thing is the annotation @ParameterizedTest, which runs the same test with several sets of values. It saves a great deal of repeated code when you have a table of cases.
The fifth thing is the method assertAll, which runs several checks and reports every failure at once instead of stopping at the first one.
The next question in this topic looks at the difference between the kinds of test.