LoginSignup
1
5

More than 3 years have passed since last update.

【JUnit5対応】Spring boot 2.2, 2.3でJUnit5を使ったテストを書く

Posted at

本記事は 『Spring boot2.2以上で、JUnit5に対応』 について記載してます。
下記の用途に参考になればー!

  1. Spring boot 2.1以下から、2.2以上にアップデート
  2. JUnit4からJUnit5への乗り換え
  3. JUnit5を記述する際、事前にJUnit4を除外したい

0. 前提

環境

  • Java 8〜(Spring boot2.2以上では、Java8, 11にサポートしています)
  • Spring boot 2.2〜

知っておくといい知識

  • Spring boot 2.2以上からは、JUnit5がデフォルト
  • JUnit4と、JUnit5は基本的に互換はない
  • 現状JUnit4と5が共存できるようになっている(いずれなくなる)

1. JUnit5を使うための依存関係

  • やること
    • junit-vintage-engineを除外する(JUnit4が動くようにする依存のため)

例1. Mavenの場合

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>

例2. Gradleの場合

testImplementation('org.springframework.boot:spring-boot-starter-test') {
    exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}

2. JUnit4関係の記述を修正

  • @RunWith が廃止された
    • 対応 ... 削除 or @ExtendWithに変更
  • @Test のimport元が変わった
    • 対応前 ... import org.junit.Test;
    • 対応後 ... import org.junit.jupiter.api.Test;
  • @Before が廃止された
    • 対応 ... @BeforeEach or @BeforeAllに変更

(参考)

↓ 参考にしたサイトです
- Spring Boot 2.2 Release Notes · spring-projects/spring-boot Wiki · GitHub
- JUnit 5 User Guide

1
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
5