JUnit 5
Junior Always asked 6 min
On this page
The question
What are the JUnit 5 lifecycle annotations, and in what order do they run?
30-second answer
@BeforeAll runs once before all tests in a class, and @AfterAll once after them; both are static by default. For every @Test, JUnit creates a new instance of the class, then runs @BeforeEach, the test and @AfterEach. @AfterEach runs even when the test fails. Use the per-test pair for cheap setup and the per-class pair for costly shared resources.
Understand it
The JUnit 5 lifecycle of one test class
Step by step@BeforeAll runs once, before any test. It is static by default, because no instance of the test class exists yet.
View as text
A log of calls grows down the left side, one line per call, and two boxes on the right stand for the two instances of the test class, each showing its cart field.
@BeforeAll runs once, before any test. It is static by default, because no instance of the test class exists yet. The log shows @BeforeAll.
JUnit creates a new CartTest instance for the first test, so its cart field starts empty. Instance 1 appears with an empty cart.
@BeforeEach runs on that instance, then the @Test method. The test adds a book, so this instance holds one item.
@AfterEach runs after the test, and it still runs when the test fails. Use it to release what @BeforeEach set up.
For the next test, JUnit creates another instance. Its cart is empty again: nothing a test wrote to a field carries over. Instance 1 fades as discarded, and instance 2 appears with an empty cart.
@BeforeEach, the second @Test and @AfterEach run on the new instance. The method order is fixed but not obvious, so never depend on it.
@AfterAll runs once, after every test in the class, to release shared, costly resources such as a server or a container. A mark reads once per class.
A log of calls grows down the left side, one line per call, and two boxes on the right stand for the two instances of the test class, each showing its cart field.
@BeforeAll runs once, before any test. It is static by default, because no instance of the test class exists yet. The log shows @BeforeAll.
JUnit creates a new CartTest instance for the first test, so its cart field starts empty. Instance 1 appears with an empty cart.
@BeforeEach runs on that instance, then the @Test method. The test adds a book, so this instance holds one item.
@AfterEach runs after the test, and it still runs when the test fails. Use it to release what @BeforeEach set up.
For the next test, JUnit creates another instance. Its cart is empty again: nothing a test wrote to a field carries over. Instance 1 fades as discarded, and instance 2 appears with an empty cart.
@BeforeEach, the second @Test and @AfterEach run on the new instance. The method order is fixed but not obvious, so never depend on it.
@AfterAll runs once, after every test in the class, to release shared, costly resources such as a server or a container. A mark reads once per class.
Takeaway: BeforeAll and AfterAll run once per class; BeforeEach and AfterEach wrap every test, and each test gets a fresh instance of the class.
Reorder a test into Arrange-Act-Assert
BuildThe lines of a test that pays with a 10% coupon are mixed up. Put them back so the test reads Arrange, then Act, then Assert.
Drag a piece, or select it and then select a place.
View as text
Four line positions inside a test method, grouped under Arrange, Act and Assert labels on the left. The lines of a test that pays with a 10% coupon are mixed up. Put them back so the test reads Arrange, then Act, then Assert.
The right order is: var cart = new Cart(), to create the object under test. cart.add(item("book", 20)), to put it in the state this case needs. int paid = cart.pay("TEN"), the single call to the behavior under test. assertEquals(18, paid), the check on the outcome of that call.
Setup first, then a single call to the behavior, then the check. Anyone can see what the test does and why it fails. Once solved, a mark reads that the test passes: 18 paid.
Four line positions inside a test method, grouped under Arrange, Act and Assert labels on the left. The lines of a test that pays with a 10% coupon are mixed up. Put them back so the test reads Arrange, then Act, then Assert.
The right order is: var cart = new Cart(), to create the object under test. cart.add(item("book", 20)), to put it in the state this case needs. int paid = cart.pay("TEN"), the single call to the behavior under test. assertEquals(18, paid), the check on the outcome of that call.
Setup first, then a single call to the behavior, then the check. Anyone can see what the test does and why it fails. Once solved, a mark reads that the test passes: 18 paid.
Takeaway: A readable test has three parts: arrange the inputs, act with one call, and assert on the result. A test with several acts is several tests.
In code
class CartTest {
Cart cart; // a fresh instance per test, so no state leaks
@BeforeEach
void setUp() { cart = new Cart(); }
@Test
void paysTenPercentLessWithCoupon() {
cart.add(item("book", 20)); // Arrange
int paid = cart.pay("TEN"); // Act
assertEquals(18, paid); // Assert
}
@Test
void rejectsNegativePrice() {
var e = assertThrows(IllegalArgumentException.class, () -> cart.add(item("pen", -1)));
assertEquals("price must not be negative", e.getMessage());
}
}@ParameterizedTest(name = "{0} pays {1}")
@CsvSource({ "0, 0", "20, 18", "100, 90" })
void takesTenPercentOff(int total, int expected) {
assertEquals(expected, Discounts.tenPercent(total));
}@Test
void registersUser() {
User u = service.register("Ana", "ana@example.com");
assertAll(
() -> assertEquals("Ana", u.name()),
() -> assertEquals("ana@example.com", u.email()),
() -> assertNotNull(u.id()));
}Solve it
A test passes alone but fails when the whole class runs
addsItem() passes when run by itself. Run with the rest of CartTest, it fails: the cart already holds an item.
Nobody changed the test. Find the cause and make the tests independent.
- Confirm order dependence. Pass alone, fail together: some state outlives one test and leaks into the next.
- Look for state that is shared. JUnit 5 creates a new test instance per method, so instance fields reset. A
staticfield, a singleton, a system property or database rows do not. - Find it.
CartTestkeepsstatic Cart cart, built once in@BeforeAll. Every test adds to the same cart. - Fix it. Build fresh state in
@BeforeEach, or clean shared resources in@AfterEach. Do not pin an order with@TestMethodOrderto hide the leak. - Check. Run the class several times with a random method order; every order passes.
class LeakyCartTest {
Wrong static Cart cart;
@BeforeAll
Wrong static void setUp() { cart = new Cart(); } // one cart for every test
@Test void addsItem() { cart.add("pen"); assertEquals(1, cart.size()); }
}
class CartTest {
Right private Cart cart;
@BeforeEach
Right void setUp() { cart = new Cart(); } // a new cart before each test
@Test void addsItem() { cart.add("pen"); assertEquals(1, cart.size()); }
}junit.jupiter.testmethod.order.default=org.junit.jupiter.api.MethodOrderer$RandomHow to answer
- A new instance per test means fields never carry state from one test to the next.
@AfterEachand@AfterAllare for cleanup, and they run after failures too.@TestInstance(Lifecycle.PER_CLASS)shares one instance and lets@BeforeAllbe non-static.- JUnit 4 names were
@Before,@After,@BeforeClassand@AfterClass.
Common mistakes
- Expecting a field set in one test to be visible in the next.
- Putting slow setup, such as starting a server, in
@BeforeEach.
Follow-up questions
Which JUnit 5 assertions do you use most, and when?
assertEquals(expected, actual) for values, assertTrue and assertFalse for conditions, and assertThrows to check an exception; it returns the exception so you can check its message. assertAll runs several assertions and reports every failure, not just the first. Many teams use AssertJ's assertThat(...) instead for readable chains and better messages.
- The expected value comes first in
assertEquals, or the failure message is backwards. assertThrowsreplaces JUnit 4's@Test(expected = ...)and pins the exact statement that throws.assertAllgroups related checks so one run shows every broken field.
var e = assertThrows(IllegalArgumentException.class,
() -> cart.add(item("pen", -1)));
assertEquals("price must not be negative", e.getMessage());
assertAll(
() -> assertEquals("ana", order.customer()),
() -> assertEquals(2, order.lines().size())); See it in the infographic: Reorder a test into Arrange-Act-Assert
How do you run the same test with different inputs in JUnit 5?
With @ParameterizedTest and a source of arguments. @ValueSource passes single values, @CsvSource passes rows of values, @EnumSource passes enum constants, and @MethodSource takes them from a static method returning a stream. JUnit runs the method once per row and reports each run as its own test, so one failing case does not hide the others.
- It needs the
junit-jupiter-paramsartifact, which thejunit-jupiteraggregate includes. name = "{0} pays {1}"makes each run readable in the report.- Prefer it over a loop inside one test, which stops at the first failing case.
See it in the infographic: The JUnit 5 lifecycle of one test class
What is the Arrange-Act-Assert pattern?
A layout for the body of a test. Arrange sets up the object and its inputs, Act calls the one behavior under test, and Assert checks the outcome. Keeping the three parts apart, often with a blank line, makes a test easy to read and makes it obvious what failed. Given-When-Then is the same idea in BDD (behavior-driven development) words.
- One act per test; a second act usually means a second test.
- Shared arrange steps move to
@BeforeEachor a helper method. - The test name should say the case and the expected outcome.
See it in the infographic: Reorder a test into Arrange-Act-Assert
What changed from JUnit 4 to JUnit 5?
JUnit 5 is split into the Platform, which launches tests; Jupiter, the new programming model; and Vintage, which still runs JUnit 4 tests. Annotations were renamed, so @Before became @BeforeEach. Runners and rules were replaced by one extension model, @ExtendWith. Test classes and methods no longer need to be public, and it added assertThrows, assertAll, nested tests and parameterized tests built in.
@RunWith(MockitoJUnitRunner.class)becomes@ExtendWith(MockitoExtension.class).- Vintage lets JUnit 4 and JUnit 5 tests run side by side during a migration.
- JUnit 5 needs Java 8 or later.
Why does JUnit create a new instance of the test class for each test method?
To keep tests isolated. Each test starts from fresh instance fields, so no test can depend on what another one left behind, and tests can run in any order or in parallel. The cost is small, because constructing a test class is cheap. State that should really be shared, such as a container, goes in static fields set up in @BeforeAll.
- It is the default
Lifecycle.PER_METHOD. - Static fields are still shared, so they can still leak state.
- Isolation is what makes running in random order or in parallel safe.
See it in the infographic: The JUnit 5 lifecycle of one test class
Can @BeforeAll be a non-static method?
Yes, with @TestInstance(Lifecycle.PER_CLASS) on the class. JUnit then creates one instance for all its tests, so @BeforeAll can use instance fields. The price is that tests share that instance, so any state one test leaves in a field is seen by the next.
Does @AfterEach run if the test fails?
Yes. JUnit runs @AfterEach methods whether the test passed, failed or threw, much like a finally block. That is why cleanup belongs there and not at the end of the test method, where a failed assertion would skip it.
Can you rely on the order of test methods?
No. The default order is deterministic but intentionally not obvious, and it is not the order in the source. Tests should not depend on each other. If you truly need an order, as in some integration scenarios, use @TestMethodOrder(OrderAnnotation.class) with @Order.
Check yourself
Show answers
- @BeforeAll once, @BeforeEach three times: Correct. The class-level pair runs once, and the method-level pair wraps every test.
- Both run three times: Incorrect. @BeforeAll runs once per class, not once per test.
- Both run once: Incorrect. @BeforeEach runs before every test method.
Show answers
- 0: Correct. Each test runs on a new instance of the class, so the field starts fresh.
- 1: Incorrect. The first test changed a different instance, which JUnit has discarded.
- It depends on the order of the tests: Incorrect. It would if the field were static; an instance field is never shared.
Show answers
- cart.pay("TEN"): Correct. It is the single call to the behavior the test is about.
- cart.add(book): Incorrect. Adding the book prepares the state, so it belongs to Arrange.
- assertEquals(18, paid): Incorrect. This line checks the outcome, so it is the Assert.