[JUnit] JUnit5 기초지식 정리( 설정, annotation, assertions )
java 개발자가 가장 많이 사용하는 테스트 프레임워크 JUnit에 대한 기초지식
많은 개발 방법론이 있지만 TDD의 핵심인 Test Code 작성을 위한 프레임워크 중 java 개발자들이 가장 많이 이용하는 프레임워크이다.
0. JUnit?
아래 intellij를 개발한 jetbatins 사이트에서 java 개발자들의 재미있는 통계를 볼 수 있다.
The State of Developer Ecosystem in 2022 Infographic
The State of Developer Ecosystem 2022 is a detailed report about the programming community, which covers the latest trends in languages, tools, technologies, and lifestyles of developers.
www.jetbrains.com
jetbrains에서 중복 투표가 가능한 통계내용 중 가장 많이 사용되는 내용을 간략히 정리하면
java version - 8버전을 60%가 사용하며 11버전은 48%, 17버전은 30%가 사용한다.
web framework - spring boot를 67%가 사용하며 Spring MVC를 41%가 사용한다.
unit test framework - JUnit을 86%가 사용하며 Mockito을 46%가 사용한다.
build system - Maven을 73%가 사용하며 gradle은 50%가 사용한다.
중복투표가 가능하다는 점을 생각하면 유닛 테스트에서 가장 많은 개발자가 JUnit + Mockito을 사용중인걸 알 수 있다.
우리가 JUnit을 공부해야하는 이유는 위 글로 충분히 설명되었다고 생각한다.
1. JUnit 5
- java version
- java 8 이상
- JUnit5 Modules
- Platform
- JUnit 플랫폼은 JVM에서 테스트 프레임워크를 시작하기 위한 기반 역할을 합니다. 또한 플랫폼에서 실행되는 테스트 프레임워크를 개발하기 위한 TestEngine API를 정의합니다. 또한 플랫폼은 JUnit 4 기반 환경의 플랫폼에서 모든 TestEngine을 실행하기 위한 JUnit 4 기반 실행기와 명령줄에서 플랫폼을 시작하기 위한 Console Launcher를 제공합니다.
- 테스트를 실행하는 기초를 제공하고 TestEngine API를 제공
- Jupiter
- JUnit Jupiter는 JUnit 5에서 테스트 및 확장을 작성하기 위한 새로운 프로그래밍 모델과 확장 모델의 조합입니다. Jupiter 하위 프로젝트는 플랫폼에서 Jupiter 기반 테스트를 실행하기 위한 TestEngine을 제공합니다.
- TestEngine API의 구현체로 JUnit5 제공
- Vintage
- JUnit Vintage는 플랫폼에서 JUnit 3 및 JUnit 4 기반 테스트를 실행하기 위한 TestEngine을 제공합니다.
- 구버전 JUnit을 실행하기 위한 TestEngine API 제공
- Platform
- 요약
- JUnit5는 java 8 이상이 필요하며 JUnit 5에서 JUnit 3, JUnit4를 실행할 수 있는 모듈을 제공하여 이전 버전을 사용하고 있더라도 테스트가 가능하다.
2. 설정
- Spring Boot 2.2+ 이상의 버전부터 JUnit 5 가 기본적으로 의존성에 추가되기에 별도의 세팅이 필요하지 않다.
testImplementation("org.springframework.boot:spring-boot-starter-test")
test {
useJUnitPlatform()
}
- Maven
<!-- ... -->
<dependencies>
<!-- Only needed to run tests in a version of IntelliJ IDEA that bundles older versions -->
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<!-- JUnit 3,4 버전을 사용하지 않으면 세팅하지 않아도 된다. -->
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>5.9.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
- Gradle
testImplementation(platform("org.junit:junit-bom:5.9.2"))
testRuntimeOnly("org.junit.platform:junit-platform-launcher") {
because("Only needed to run tests in a version of IntelliJ IDEA that bundles older versions")
}
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
// JUnit 3,4를 사용하지 않으면 세팅하지 않아도 된다.
testRuntimeOnly("org.junit.vintage:junit-vintage-engine")
test {
useJUnitPlatform()
}
3. annotation
annotation | 설명 | |
@TestFactory | 동적 테스트를 위한 테스트 팩토리인 메서드를 나타냅니다. | |
@DisplayName | 테스트 클래스 또는 테스트 메서드에 대한 사용자 지정 표시 이름을 정의합니다. | |
@Nested | 주석이 달린 클래스가 중첩된 비정적 테스트 클래스임을 나타냅니다. | |
@Tag | 테스트 필터링을 위한 태그 선언 | |
@ExtendWith | 사용자 정의 확장 등록 | |
@BeforeEach | 주석이 달린 메서드가 각 테스트 메서드 전에 실행됨을 나타냅니다(이전에는 @Before ). | |
@AfterEach | 주석이 달린 메서드가 각 테스트 메서드 후에 실행됨을 나타냅니다(이전에는 @After ). | |
@BeforeAll | 주석이 달린 메서드가 현재 클래스의 모든 테스트 메서드보다 먼저 실행됨을 나타냅니다(이전에는 @BeforeClass ). | |
@AfterAll | 주석이 달린 메서드가 현재 클래스의 모든 테스트 메서드 후에 실행됨을 나타냅니다(이전에는 @AfterClass ). | |
@Disable | 테스트 클래스 또는 메서드를 비활성화합니다(이전에는 @Ignore ). |
외 다양한 annotation이있다.
annotation에 대한 자세한 내용은 별도의 블로그를 통해 설명한다.
2023.02.25 - [IT/JAVA | Spring] - [JUnit] JUnit5 기초지식 annotation 정리
[JUnit] JUnit5 기초지식 annotation 정리
Junit5의 요약된 기초지식에 대한 내용은 아래에서 확인 가능하다. 2023.02.18 - [IT/JAVA | Spring] - [JUnit] JUnit5 기초지식 정리( 설정, annotation, assertions ) [JUnit] JUnit5 기초지식 정리( 설정, annotation, assertions
kangyb.tistory.com
SpringBootTest
2023.04.30 - [IT/JAVA | Spring] - [JUnit] spring boot 테스트하기 ( Migration from JUnit4 to JUnit5 )
[JUnit] spring boot 테스트하기 ( Migration from JUnit4 to JUnit5 )
Junit5의 요약된 기초지식에 대한 내용은 아래에서 확인 가능하다. 2023.02.18 - [IT/JAVA | Spring] - [JUnit] JUnit5 기초지식 정리( 설정, annotation, assertions ) [JUnit] JUnit5 기초지식 정리( 설정, annotation, assertions
kangyb.tistory.com
4. Assertions
테스트 조건을 설정하고 성공 여부 등을 판단하기 위한 유틸리티 메서드 모음
module : org.junit.jupiter.api
static import를 세팅하면 가독성도 좋아지고 편하게 사용가능하다.
import static org.junit.jupiter.api.Assertions.*
모든 Assertions는 마지막 parameter로 Supplier<String>를 받을 수 있다.
Assertions method | 설명 | |
assertEquals(expected, actual) | expected(예상되는, 기대하는)값과 actual(실제)값이 같은지 확인한다. | |
asserNotEquals(expected, actual) | expected(예상되는, 기대하는)값과 actual(실제)값이 같지 않은지 확인한다. | |
assertNotNull(actual) | 값이 Not Null인지 확인하다. | |
assertNull(actual) | 값이 Null인지 확인하다. | |
assertFalse(boolean condition) | 상태가 False인지 확인한다. | |
assertTrue(boolean condition) | 상태가 Ture인지 확인한다. | |
assertArrayEquals( Object[] expected, Object[] actual) |
expected(예상되는, 기대하는) 배열과 actual(실제) 배열이 완전히 동일한지 확인한다. 모두 Null이면 같은것으로 판단한다. | |
assertIterableEquals( Iterable<?> expected, Iterable<?> actual) |
expected(예상되는 iterable)과 actual(실제 iterable)이 완전히 동일한지 확인한다. 모두 Null이면 같은것으로 판단한다. | |
assertAll(...) | 내부의 모든 assertions를 확인한다. | |
assertThrows( Class<T> expectedType, Executable executable) |
expectedType(예상되는 예외)와 executable(실제 예외)이 같은지 확인한다. | |
assertTimeout( Duration timeout, Executable executable) |
timeout(주어진 제한) 시간이 초과되기 전에 제공된 executable(실행 파일)의 실행이 완료되는지 확인합니다. |
외 다양한 Assertions method가 있다.
Assertions method에 대한 자세한 내용은 별도의 블로그를 통해서 설명한다.
Reference
https://junit.org/junit5/docs/current/user-guide/