Video in progress
In JUnit 5, when are the @BeforeEach and @AfterEach methods called, and how many times?
@BeforeEach runs before every @Test method, and @AfterEach runs after each one. If the class has 5 tests, each of them runs 5 times.
📖 Answer
These annotations exist to give every test a clean starting state.
class CartTest {
private Cart cart;
@BeforeEach
void setUp() {
cart = new Cart(); // every test starts with a fresh cart
}
@AfterEach
void tearDown() {
// if there's a temp file or an open resource, close it here
}
@Test
void bosh_savat_summasi_nol() {
assertEquals(0, cart.total());
}
@Test
void mahsulot_qoshilsa_soni_oshadi() {
cart.add(new Item("olma", 3000));
assertEquals(1, cart.size());
}
}
The order is setUp → test → tearDown, then it starts over for the next test. In JUnit 4 these were called @Before and @After, so don't get confused when you see them in old code.
One catch: @AfterEach runs even if the test fails, so it's better to put cleanup code here than inside the test.
Sign up to mark studied questions and save your progress.