Lifecycle: before and after every test
A test needs a subject. Building it inside every method is repetition, and building it in a field is a trap, because the framework makes a new test object for every method and a field initialiser therefore runs per test. JUnit names the four moments a class can act on, and this page prints them in the order a run sees them.
The class under test
A basket with a list inside it, a size and a total. It holds state, which is what makes it a fixture: every test wants a basket of its own, and a test that adds a pear must not see the pear of the test before it:
import java.util.ArrayList;
import java.util.List;
public class Basket {
private final List<String> items = new ArrayList<>();
void add(String item) {
items.add(item);
}
int size() {
return items.size();
}
int total(int pricePerItem) {
return items.size() * pricePerItem;
}
public static void main(String[] args) {
Basket basket = new Basket();
basket.add("apple");
basket.add("pear");
System.out.println("items: " + basket.size());
System.out.println("total at 3: " + basket.total(3));
}
}
Two items at three each is six, which is the program's second line. The test below never uses the main; it builds the same object and checks the two methods that the program only demonstrates.
@BeforeEach and @AfterEach
@BeforeEach runs before every test method and @AfterEach after it, whatever the method did. The field basket is assigned there, so each test starts from one apple and no test can see what another one added. The counter tests is static because it outlives the object, which the last section uses:
@BeforeAll and @AfterAll
@BeforeAll runs once before the first test of the class and @AfterAll once after the last, and both must be static unless the class changes its lifecycle. They are the place for a resource that is expensive and shared: a database connection, a server, a log file. The counter below is set there, so the value the last line prints is the number of tests that ran and not the number of methods that exist.
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class BasketTest {
static int tests;
Basket basket;
@BeforeAll
static void beforeAll() {
tests = 0;
System.out.println("before all: the class is loaded once");
}
@BeforeEach
void setUp() {
basket = new Basket();
basket.add("apple");
tests++;
System.out.println("before each: a fresh basket");
}
@AfterEach
void tearDown() {
System.out.println("after each: " + basket.size() + " item(s)");
}
@AfterAll
static void afterAll() {
System.out.println("after all: " + tests + " test(s) ran");
}
@Test
@Order(1)
void startsWithOneItem() {
assertEquals(1, basket.size());
}
@Test
@Order(2)
void addsAnItem() {
basket.add("pear");
assertEquals(2, basket.size());
assertEquals(6, basket.total(3));
}
}
The order, printed
The prints make the lifecycle visible. before all comes once, before each and after each come twice, between them in pairs, and after all closes the run. The after each line of the second test says two items, because that test added a pear; the first says one, which proves the fixture was fresh.
The methods have an explicit order through @Order, and that is a choice this page makes so the output is the same on every run. A test that needs the order to be right is a test that depends on another one, and the rule is that tests in a project should pass in any order: the annotation is for a printed demonstration like this one, not for a fixture that builds on its predecessor.
The run
javac -Xlint:all -cp /opt/java-tools/junit-platform-console-standalone.jar -d out Basket.java BasketTest.java
java -cp out Basket
items: 2
total at 3: 6
junit execute --class-path out --select-class BasketTest --disable-ansi-colors
Thanks for using JUnit! Support its development at https://junit.org/sponsoring
before all: the class is loaded once
before each: a fresh basket
after each: 1 item(s)
before each: a fresh basket
after each: 2 item(s)
after all: 2 test(s) ran
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│ └─ BasketTest ✔
│ ├─ startsWithOneItem() ✔
│ └─ addsAnItem() ✔
└─ JUnit Vintage ✔
Test run finished after 191 ms
[ 4 containers found ]
[ 0 containers skipped ]
[ 4 containers started ]
[ 0 containers aborted ]
[ 4 containers successful ]
[ 0 containers failed ]
[ 2 tests found ]
[ 0 tests skipped ]
[ 2 tests started ]
[ 0 tests aborted ]
[ 2 tests successful ]
[ 0 tests failed ]
What the lifecycle is for
The four annotations are the whole fixture, and the object rule behind them is the one to remember: a new instance of the test class is made for every test method, so an instance field is fresh without any code, and the field initialiser is the first thing that runs. A static field is shared by all the methods of the class, and the framework does not reset it between runs of the same class.
A resource that must be closed goes in @AfterEach or @AfterAll, and a test that throws still reaches it, because the framework calls the after methods on a failure too. That is the same guarantee as a finally, one level up, and the exceptions page shows the case where the assertion is the exception.
What comes next
The fixture here cannot fail. The next page tests code that throws on purpose: assertThrows, the exception that was not thrown, the message and the cause, and the difference between a test that expects a failure and a test that fails.
The Java course covers the same annotations in lesson 127, and the try-with-resources that closes a fixture without an @AfterEach is lesson 098.
The code on this page was compiled with OpenJDK 21.0.13 (javac) and run with the JUnit Platform Console Launcher 1.14.3 on Alpine Linux in a Docker container. The time in the report is that machine's and changes between runs.
Article author: Arthur Isaev