Spring
[Spring Boot] JUnit4 vs JUnit5
haleylog
2025. 3. 12. 17:11
1. JUnit 이란?
단위 테스트와 자동화된 테스트를 쉽게 작성하고 실행할 수 있도록 도와주는 Testing Framework
2. SpringBoot + JUnit
Spring Boot 프로젝트의 기본 모듈인 spring-boot-starter-test 는 JUnit 라이브러리를 포함하고 있다.
Spring Boot 버전 | 기본 JUnit Version |
Spring Boot 1.x | JUnit4 |
Spring Boot 2.0.x | JUnit4 |
Spring Boot 2.1.x ~ | JUnit5 |
Spring Boot 3.x | JUnit5 |
3. JUnit4 vs JUnit5
구조
JUnit4 : 모듈화 X. 단일 라이브러리
JUnit5 : 모듈화 O. JUnit Platform + JUnit Jupiter + JUnit Vintage
- JUnit Platform: 다양한 테스트 엔진을 실행할 수 있는 환경 제공
- JUnit Jupiter: 테스트 API와 어노테이션을 제공 @Test, @BeforeEach, @AfterEach 등
- JUnit Vintage: JUnit 4와 호환되도록 지원
라이프사이클 어노테이션
Life Cycle | Junit4 | JUnit5 |
모든 테스트 메서드 실행 전 실행 | @BeforeClass | @BeforeAll |
각 테스트 메서드 실행 전 실행 | @Before | @BeforeEach |
테스트 메서드 실행 | @Test | @Test |
각 테스트 메서드 실행 후 실행 | @After | @AfterEach |
모든 테스트 메서드 실행 후 실행 | @AfterClass | @AfterAll |
기타 기능 어노테이션
기능 | JUnit4 | JUnit5 |
테스트 비활성화 | @Ignore | @Disabled |
테스트 확장 | @RunWith | @ExtendWith |
동적 테스트 | - | @TestFactory |
조건부 테스트 실행 | - | @EnabledIf, @DisabledIf, @Tag 등 |
728x90
4. JUnit5 사용예시
class MyTestClass {
@BeforeEach
void setUp() {
System.out.println("각 테스트 실행 전 설정");
}
@Test
void testAddition() {
int result = 2 + 3;
assertEquals(5, result);
}
@Test
@Disabled
void testSubtraction() {
int result = 5 - 3;
assertEquals(2, result);
}
@Test
void testMultiplication() {
int result = 2 * 3;
assertEquals(4, result);
}
@AfterAll
static void tearDownAll() {
System.out.println("모든 테스트 실행 후 정리 작업");
}
}
실행 결과 :
각 테스트 실행 전 설정
각 테스트 실행 전 설정
Expected : 4 Actual : 6
모든 테스트 실행 후 정리 작업
1. testAddition() 실행 전 setUp() 메세지 출력
2. testAddition() 실행 성공하여 별도 메세지 출력 X
3. testSubtraction() 은 Disabled 되어 실행되지 않음
4. testMultiplication() 실행 전 setUp() 메세지 출력
5. testMultiplication() 실행 실패하여 기대값, 실행값 메세지 출력
6. 모든 테스트 실행 완료하여 tearDownAll() 메세지 출력
728x90
반응형