KotlinでJUnit5を使う
概要
KotlinとJUnit5を使うためのできるだけシンプルな構成を作ったときのメモです。
環境
まずはKotlinの準備
KotlinのReferenceに沿って設定すればOK。 今回はMavenを使っています。 https://kotlinlang.org/docs/reference/using-maven.html
Kotlinを使うために追加するのはこんな感じ。
<properties> <kotlin.version>1.2.51</kotlin.version> </properties> <dependencies> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib</artifactId> <version>${kotlin.version}</version> </dependency> </dependencies> <build> <sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory> <testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory> <plugins> <plugin> <artifactId>kotlin-maven-plugin</artifactId> <groupId>org.jetbrains.kotlin</groupId> <version>${kotlin.version}</version> <executions> <execution> <id>compile</id> <goals> <goal>compile</goal> </goals> </execution> <execution> <id>test-compile</id> <goals> <goal>test-compile</goal> </goals> </execution> </executions> </plugin> <plugins> </build>
次はJUnit5の設定
ここにJUnit5を追加していきます。
こちらもReferenceに沿って依存を追加すれば大丈夫。
JUnit5を使うには最低限junit-jupiter-engine
を依存関係に含めることと、
Mavenから実行するにはmaven-surefire-plugin
が必要。
<properties> ... <junit.jupiter.version>5.2.0</junit.jupiter.version> ... </properties> <dependencies> ... <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>${junit.jupiter.version}</version> <scope>test</scope> </dependency> ... </dependencies> <build> ... <plugins> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.0</version> </plugin> </plugins> </build>
このブログの公開時にはmaven-surefire-plugin
のバージョンが2.21.0
を使うように書かれていますが、
2.22.0を使っても問題ないようです。
適当なクラスを作成
テストを実行するために適当なクラスを作ります。
今回はただhoge
という文字列を返すだけの関数を作りました。
package com.example.panage.junit5 class Hoge { fun say(): String = "hoge" }
テストクラスを作成
テストクラスを作成します。
テストを実行したい関数に@org.junit.jupiter.api.Test
アノテーションを付与すればOK。
package com.example.panage.junit5 import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test internal class HogeTest { @Test fun sayのテスト() { // setup val hoge = Hoge() // expect Assertions.assertEquals("hoge", hoge.say()) } }
hoge
という文字列が返ってくるはずなので、Assertions.assertEquals
で比較しています。
[INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running com.example.panage.junit5.HogeTest [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.013 s - in com.example.panage.junit5.HogeTest [INFO] [INFO] Results: [INFO] [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------
雑感
KotlinもJUnitも公式のReferenceが整っているので、手順通りに進めれば問題ありませんでした。
テストクラスもいままでと同じように書けるので違和感もなさそうです。