Search⌘ K
AI Features

@BeforeEach and @AfterEach Annotation

Explore how JUnit 5 creates a new test class instance for each test method and how the @BeforeEach and @AfterEach annotations run setup and teardown code around each test. Understand their role in organizing common test logic for cleaner, more maintainable unit tests.

@Test and Constructor

In Junit 5 for each test, a new instance of test class is created. So, for e.g. if a class has two @Test methods than two instances of test class will be created, one for each test. Thus, the constructor of the test class will be called as many times as there is the number of @Test methods. Let’s look at the demo:-

JUnit5 (Java 1.8)
package io.educative.junit5;
import org.junit.jupiter.api.Test;
public class LifecycleTest {
public LifecycleTest() {
System.out.println("LifecycleTest - Constructor got executed !!!");
}
@Test
public void testOne() {
System.out.println("LifecycleTest - testOne() got executed !!!");
}
@Test
public void testTwo() {
System.out.println("LifecycleTest - testTwo() got executed !!!");
}
}
Output of the test
Output of the test
...