What if you could stop repeating boring setup and cleanup code and let JUnit handle it for you?
Why BeforeEachCallback and AfterEachCallback in JUnit? - Purpose & Use Cases
Imagine you have many tests to run, and before each test, you need to set up some data or prepare the environment. After each test, you must clean up to avoid problems in the next test. Doing this by hand means repeating the same setup and cleanup code inside every test.
Writing setup and cleanup code inside every test is slow and boring. It's easy to forget to clean up, which causes tests to fail unpredictably. This manual repetition wastes time and makes tests hard to maintain.
@BeforeEach and @AfterEach let you write setup and cleanup code once, and JUnit runs it automatically before and after each test. This keeps tests clean, avoids mistakes, and saves time.
void test1() {
setup();
// test code
cleanup();
}
void test2() {
setup();
// test code
cleanup();
}@BeforeEach
void setup() { /* prepare */ }
@AfterEach
void cleanup() { /* clean */ }
@Test
void test1() { /* test code */ }
@Test
void test2() { /* test code */ }You can write many tests that run safely and independently without repeating setup and cleanup code.
Think of baking cookies: you prepare the dough once before each batch and clean the kitchen after each batch. This keeps every batch fresh and avoids mixing flavors.
Manual setup and cleanup in every test is slow and error-prone.
@BeforeEach and @AfterEach automate this process.
This leads to cleaner, safer, and easier-to-maintain tests.