테스트 수명 주기 및 순서
고급 수명 주기 어노테이션을 사용해 테스트 실행 순서를 제어하고 테스트 설정 및 정리를 관리합니다.
테스트 수명 주기 및 순서은(는) CoddyKit의 무료 Testing Mastery: JUnit, Mockito & Integration Tests 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Testing Mastery: JUnit, Mockito & Integration Tests 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Testing Mastery: JUnit, Mockito & Integration Tests 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
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.
}Class-Level Teardown: @AfterAll
Similarly, you might need to clean up resources once after all tests in a class have completed. The @AfterAll annotation marks a method to run after all test methods in the class.
Like @BeforeAll, it must be static by default.
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class AfterAllDemo {
private static StringBuilder log = new StringBuilder();
@BeforeAll
static void setup() {
log.append("-> @BeforeAll: Setup for AfterAllDemo.\n");
}
@Test
void testOne() {
log.append(" -> @Test: Running testOne.\n");
assertTrue(true);
}
@Test
void testTwo() {
log.append(" -> @Test: Running testTwo.\n");
assertTrue(true);
}
@AfterAll
static void teardown() {
log.append("-> @AfterAll: Teardown for AfterAllDemo.\n");
System.out.println("--- Execution Log ---");
System.out.println(log.toString()); // See the full order
System.out.println("--- End Log ---");
}
}@TestInstance: PER_CLASS Lifecycle
By default, JUnit creates a new instance of your test class for each test method (Lifecycle.PER_METHOD). This ensures test isolation.
If you need @BeforeAll and @AfterAll methods to be non-static, or if you want to share state across all tests in a class, you can switch the test instance lifecycle to Lifecycle.PER_CLASS.
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import static org.junit.jupiter.api.Assertions.assertEquals;
@TestInstance(Lifecycle.PER_CLASS) // Allows non-static @BeforeAll/@AfterAll
public class PerClassLifecycleDemo {
private int counter = 0; // Instance variable, shared across tests
@BeforeAll // No longer needs to be static!
void setupPerClass() {
counter = 10;
System.out.println("-> @BeforeAll (PER_CLASS). Counter: " + counter);
}
@Test
void testIncrementOne() {
counter++;
System.out.println(" -> @Test 1. Counter: " + counter);
assertEquals(11, counter); // Shared state is modified
}
@Test
void testIncrementTwo() {
counter++;
System.out.println(" -> @Test 2. Counter: " + counter);
assertEquals(12, counter); // Counter continues from previous test
}
@AfterAll // No longer needs to be static!
void teardownPerClass() {
System.out.println("-> @AfterAll (PER_CLASS). Final Counter: " + counter);
}
}Test Ordering: When to Use
Ideally, JUnit tests should be independent and run correctly in any order. Relying on a specific order can make your tests fragile and harder to maintain.
However, there are specific scenarios where explicit ordering might be useful:
- Testing a complex workflow with clear, sequential steps.
- Optimizing performance by grouping fast tests or tests with shared expensive setup.
- Working with legacy systems that demand a certain interaction sequence.
@TestMethodOrder Annotation
To define an execution order for test methods within a class, you use the @TestMethodOrder annotation at the class level. It takes a MethodOrderer implementation as an argument.
JUnit 5 provides several built-in strategies:
Alphanumeric.class: Orders by method name alphabetically.OrderAnnotation.class: Uses the@Orderannotation.Random.class: Randomizes the order.DisplayName.class: Orders by method display names.
Alphanumeric Method Order
Let's see MethodOrderer.Alphanumeric.class in action. JUnit will simply sort test methods based on their names in alphabetical order.
This is a simple way to get a predictable order if your method names naturally follow a sequence.
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.MethodOrderer.Alphanumeric;
import static org.junit.jupiter.api.Assertions.assertTrue;
@TestMethodOrder(Alphanumeric.class) // Tests run A, B, C
public class AlphanumericOrderDemo {
@Test
void testA_First() {
System.out.println("-> Running testA_First");
assertTrue(true);
}
@Test
void testC_Third() {
System.out.println("-> Running testC_Third");
assertTrue(true);
}
@Test
void testB_Second() {
System.out.println("-> Running testB_Second");
assertTrue(true);
}
}Custom Order with @Order
For fine-grained control, combine @TestMethodOrder(MethodOrderer.OrderAnnotation.class) with the @Order(value) annotation on individual test methods. Lower value numbers mean earlier execution.
This allows you to define a precise, custom order for your tests.
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import static org.junit.jupiter.api.Assertions.assertTrue;
@TestMethodOrder(OrderAnnotation.class) // Activate @Order annotation
public class CustomOrderDemo {
@Test
@Order(2) // This test runs second
void processStepTwo() {
System.out.println("-> Running processStepTwo");
assertTrue(true);
}
@Test
@Order(1) // This test runs first
void initializeSystem() {
System.out.println("-> Running initializeSystem");
assertTrue(true);
}
@Test
@Order(3) // This test runs third
void finalizeReport() {
System.out.println("-> Running finalizeReport");
assertTrue(true);
}
}Ordering Best Practices
While powerful, explicit test ordering should be used with caution:
- Prioritize Independence: Each test should ideally be able to run on its own.
- Readability: Over-ordering can make tests harder to understand and maintain.
- Maintenance Burden: Changes to the system might require re-evaluating and updating order values.
Only use ordering when there's a strong, justified reason, and prefer @Order for clear intent.
Lifecycle & Order Check
Consider the following JUnit 5 test class:
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class QuizTest {
private int sharedValue = 0;
@BeforeAll
void setup() {
sharedValue = 10;
System.out.println("BeforeAll: sharedValue = " + sharedValue);
}
@Test
@Order(2)
void testB() {
sharedValue += 2;
System.out.println(" TestB: sharedValue = " + sharedValue);
assertEquals(13, sharedValue);
}
@Test
@Order(1)
void testA() {
sharedValue += 1;
System.out.println(" TestA: sharedValue = " + sharedValue);
assertEquals(11, sharedValue);
}
@AfterAll
void teardown() {
System.out.println("AfterAll: sharedValue = " + sharedValue);
}
}What will be the final value of sharedValue printed in the @AfterAll method?
Recap: Lifecycle & Ordering
In this lesson, you mastered advanced JUnit 5 features for controlling test execution:
- Class-Level Lifecycle:
@BeforeAlland@AfterAllfor one-time setup/teardown. - Instance Lifecycle:
@TestInstance(Lifecycle.PER_CLASS)to enable shared state and non-static class-level hooks. - Test Method Ordering:
@TestMethodOrder(with strategies likeAlphanumericorOrderAnnotation) to define execution order. - Custom Order:
@Orderfor precise control over method sequence.
Remember to use explicit ordering judiciously, prioritizing independent and robust tests!
자주 묻는 질문
“테스트 수명 주기 및 순서” 강의는 무료인가요?
네 — “테스트 수명 주기 및 순서” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Testing Mastery: JUnit, Mockito & Integration Tests 강의 전체를 잠금 해제할 수 있습니다. Testing Mastery: JUnit, Mockito & Integration Tests 강의에는 총 4개의 강의가 포함되어 있습니다.
“테스트 수명 주기 및 순서”에서 뭘 배우나요?
고급 수명 주기 어노테이션을 사용해 테스트 실행 순서를 제어하고 테스트 설정 및 정리를 관리합니다. 브라우저에서 직접 실행하는 실습 코드로 Testing Mastery: JUnit, Mockito & Integration Tests을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Testing Mastery: JUnit, Mockito & Integration Tests을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Testing Mastery: JUnit, Mockito & Integration Tests은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“테스트 수명 주기 및 순서” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Testing Mastery: JUnit, Mockito & Integration Tests 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Testing Mastery: JUnit, Mockito & Integration Tests 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 테스트 수명 주기 및 순서
- 매개변수화 테스트와 동적 테스트
- 예외 테스트 및 시간 제한
- 조건부 테스트와 가정