Junit5 - Migration(실전)

겔로그·2022년 12월 9일
0

Junit5

목록 보기
5/5
post-thumbnail

Junit4 -> Junit 5 migration 과정

오늘은 실질적으로 Junit 4-> Junit 5로 migration을 진행해볼 예정입니다.
기존에 사용하던 코드를 junit4 -> junit5로 migration 하면서 고려했던 내용 및 주의사항에 대해 공유드리겠습니다.

다음 포스팅에서는 junit5를 실질적으로 다루는 코드들을 작성해 보겠습니다.

1. Dependency 주입

Spring Boot는 2.2 부터 JUnit5가 기본으로 채택되었습니다.

pom.xml

  1. maven-surefire-plugin 2.22.0 버전 이상 plugin 추가
<dependency>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.1</version>
</dependency>
  1. Spring Boot 2.2 이상 버전 spring-boot-starter-test dependency 추가
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring-boot.version}</version>
<scope>test</scope>
  1. 기존 junit4와 관련된 dependency 제거
<!-- 제거 해야합니다 -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>${junit.version}</version> <!-- 4.12 -->
    <scope>test</scope>
</dependency>

주의사항

다음과 같이 진행할 경우 다음 오류가 발생할 수 있습니다.
Caused by: java.lang.ClassNotFoundException: org.junit.jupiter.api.extension.ScriptEvaluationException

관련 내용을 stack overflow에서 확인했을 경우 다음과 같은 답변을 확인할 수 있습니다.

I have got the same issue with org.junit.jupiter:junit-jupiter:5.5.2. It works like a charm by upgrading the version to 5.6.2. (and also the others junit-jupiter-engine, junit-jupiter-api)

org.junit.jupiter:junit-jupiter:5.5.2를 이용하는 spring-boot-starter-test dependency는 해당 dependency를 exclude하며 5.6.2 버전을 Import 합니다.

따라서 다음과 같이 수정하여 사용하였습니다.

<dependency>
	<groupId>org.junit.jupiter</groupId>
	<artifactId>junit-jupiter</artifactId>
	<version>5.6.3</version>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-test</artifactId>
	<version>${spring-boot.version}</version>
	<exclusions>
		<exclusion>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter</artifactId>
		</exclusion>
	</exclusions>
	<scope>test</scope>
</dependency>

2. Migration

junit4와 junit5의 변경된 부분은 크게 두 가지 부분이 존재합니다.

  • annotation
  • dependency (org.junit.jupiter.api 사용)

2-1 annotation

annotation은 크게 다음과 같은 내용들이 변경되었습니다.

  1. @RunWith(SpringRunner.class) -> @ExtendWith(SpringExtension.class)
  2. @Rule -> @ExtendWith
  3. @Before, @After -> @BeforeEach, @AfterEach
  4. @BeforeClass, @AfterClass -> @BeforeAll, @AfterAll
  5. @Ignore -> @Disabled or @DisabledIf(조건문)

2-2 dependency

  1. junit5 는 org.junit.jupiter.api를 사용합니다.
  2. 기존에 사용하던 org.junit.Assert는 AssertJ, Hamcrest, Truth 등으로 변경합니다.

Reference

profile
Gelog 나쁜 것만 드려요~

0개의 댓글

관련 채용 정보