Lifecycle and structure
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
@BeforeEachruns before every test;@AfterEachruns after every test. JUnit makes a fresh test-class instance per test, so tests do not share fields.@BeforeAll/@AfterAllrun once per class and are static by default.@DisplayNamegives a readable name in reports.@Nestedgroups tests by situation (for example "when the cart is empty").@Disabledskips a test, but always with a reason.
Draft outline details
Demonstration
@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.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.