Test Lifecycle and Ordering
Control the execution order of tests and manage test setup/teardown using advanced lifecycle annotations.
JUnit Test Lifecycle Intro
Welcome! In this lesson, we'll dive into advanced JUnit 5 features to control how your tests run. Understanding the test lifecycle is key to managing resources and ensuring proper test setup and cleanup.
The lifecycle defines the sequence of actions JUnit takes before and after your test methods and classes.
Class-Level Setup: @BeforeAll
Sometimes, you need to perform setup operations only once for all tests within a specific test class. The @BeforeAll annotation marks a method to run before any test method in that class.
By default, @BeforeAll methods must be static. We'll see how to change this soon!
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class BeforeAllDemo {
private static StringBuilder log = new StringBuilder();
@BeforeAll
static void setupOnce() {
log.append("-> @BeforeAll: Setup done once.\n");
System.out.println("Setup for all tests.");
}
@Test
void testA() {
log.append(" -> @Test: Running testA.\n");
System.out.println(" Running testA.");
assertTrue(true);
}
@Test
void testB() {
log.append(" -> @Test: Running testB.\n");
System.out.println(" Running testB.");
assertTrue(true);
}
// The log output would typically be verified in @AfterAll or debugger.
}All lessons in this course
- Test Lifecycle and Ordering
- Parameterized and Dynamic Tests
- Exception Testing & Timeouts
- Conditional Tests and Assumptions