Java
@BeforeEach and @AfterEach
Learn setup with @BeforeEach and @AfterEach.
@BeforeEach and @AfterEach
Code that should run before each test method is marked with @BeforeEach; code that runs after each test is marked with @AfterEach. These methods handle common setup and cleanup.
import org.junit.jupiter.api.*;
class CartTest {
List<String> cart;
@BeforeEach
void setup() { cart = new ArrayList<>(); }
@AfterEach
void cleanup() { cart.clear(); }
}
Each test now runs independently; side effects from the previous test do not leak. Setup lives in one place and is not repeated. This keeps tests fast and reliable.
Class-level setup with @BeforeAll
For heavy resources (database connection, file) opened once, use @BeforeAll. This method must be static; the framework calls it once per class.
@BeforeAll
static void openDatabase() {
// connection opened once
}
@AfterAll
static void closeDatabase() {
// connection closed once
}
This shortens test time. But make sure tests do not depend on each other; otherwise errors appear when order changes. @BeforeEach is usually preferred.
Exercise Use @BeforeEach in a cart test
Write a CartTest class. Declare a List<String> cart field. In a @BeforeEach method setup, do cart = new ArrayList<>(). Write a @Test method testAdd that calls cart.add("apple") and verifies with assertEquals(1, cart.size()). Add a main method, add one item and print size().
Show example solution
import org.junit.jupiter.api.*;
import java.util.*;
class CartTest {
List<String> cart;
@BeforeEach
void setup() {
cart = new ArrayList<>();
}
@Test
void testAdd() {
cart.add("apple");
assertEquals(1, cart.size());
}
public static void main(String[] args) {
CartTest t = new CartTest();
t.setup();
t.cart.add("apple");
System.out.println(t.cart.size());
}
}
Test yourself
-
Match lifecycle annotations
- @BeforeEach
- Before each test
- @AfterEach
- After each test
- @BeforeAll
- Before the class (static)
- @AfterAll
- After the class (static)
-
Complete the BeforeAll method
@BeforeAll
____ void openResource() {
// tek seferlik kurulum
}
Show answer
@BeforeAll
static void openResource() {
// tek seferlik kurulum
}
-
What is the difference between @BeforeEach and @BeforeAll?
- BeforeEach runs before each test, BeforeAll before the class
- BeforeAll runs before each test, BeforeEach before the class
- They are the same, only the names differ
- BeforeAll runs only on error
Show answer
BeforeEach runs before each test, BeforeAll before the class — BeforeEach runs before each test, BeforeAll once before the class.
Next lesson: @ParameterizedTest