Skip to content
Ameen Abozaid
Planned lessonJNR-043-L02

Lifecycle and structure

  • Lesson 2 of 6
  • Junior
On This Lesson 4 topics

This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.

In this lesson

use the JUnit Jupiter lifecycle annotations to keep tests tidy.

Planned topics

  • @BeforeEach runs before every test; @AfterEach runs after every test. JUnit makes a fresh test-class instance per test, so tests do not share fields.
  • @BeforeAll / @AfterAll run once per class and are static by default.
  • @DisplayName gives a readable name in reports.
  • @Nested groups tests by situation (for example "when the cart is empty").
  • @Disabled skips a test, but always with a reason.
Draft outline details

Demonstration

java
@DisplayName("Cart")
class CartTest {
    Cart cart;
    @BeforeEach void setUp() { cart = new Cart(); }

    @Nested @DisplayName("when empty")
    class WhenEmpty {
        @Test void totalIsZero() { assertEquals(BigDecimal.ZERO, cart.total()); }
    }
}

Check your understanding

How many times does @BeforeEach run for a class with four tests?

Show answer

Four.

Practice

Apply this lesson with the module's lab, exercises and quiz.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.