はじめに
単体テストをしていく際に、新しくなったJUnit5を使用することが決定し、少し躓くことがあったので、備忘録として投稿します。
開発環境
Spring Boot 2.3.4
kotlin 1.3.7
Gradle
JUnit5
上記のバージョンでテスト用の設定を追記していきます。
Gradle設定ファイル書き換え
dependencies {
- testImplementation 'org.springframework.boot:spring-boot-starter-test'
+ testCompile('org.springframework.boot:spring-boot-starter-test') {
+ exclude module: 'org.junit.vintage'
+ }
+ testImplementation('org.junit.jupiter:junit-jupiter:5.4.0')
}
+ test {
+ useJUnitPlatform()
+ }
順番に、
1.JUnit5を追加する
+ testImplementation('org.junit.jupiter:junit-jupiter:5.4.0')
こちらのJUnit5の追加だけでは、JUnit4との依存関係のエラーが発生してしまう。
2.JUnit4の依存関係を解消する
- testImplementation 'org.springframework.boot:spring-boot-starter-test'
+ testCompile('org.springframework.boot:spring-boot-starter-test') {
+ exclude module: 'org.junit.vintage'
+ }
sterterを使用している場合は初期でJUnit4が導入されており、'org.junit.vintage'を除くことで動くようになります。
JUnit Vintage:プラットフォーム上でJUnit3およびJUnit4ベースのテストを実行するためのTestEngineを提供するライブラリ
3. JUnit platform を使う設定を追記
+ test {
+ useJUnitPlatform()
+ }
設定は以上になります。
最後に
当たり前かもしれませんが、JUnit5では、JUnit4と変更点があり、注意する点もいくつか存在します。
・インポート
JUnit 5では、アノテーションとクラスに新しいorg.junit.jupiterパッケージが使われています。
例:org.junit.Testはorg.junit.jupiter.api.Testに変更
・アノテーションも諸々変更されています。
- @Test(expected = Exception.class)
+ @Test
- @Before
+ @BeforeEach
- @After
+ @AfterEach
- @BeforeClass
+ @BeforeAll
- @AfterClass
+ @AfterAll
- @Ignore
+ @Disabled
- @Category
+ @Tag
- @Rule
- @ClassRule
+ @ExtendWith
+ @RegisterExtension
・アサーション
JUnit 5のアサーションは、org.junit.jupiter.api.Assertionsに含まれるようになっています。
assertEquals()やassertNotNull()など、引数の順番の変更やアノテーションからアサーションとして代替されているものも存在します。
JUnit5には他にもメンテナンス性の向上やその他便利な機能も充実しているとのことで、積極的に使用していきたいと思ってます。