Kotlinのテストフレームワーク
色々あるけど、今回はJetBrainsが開発しているSpekを試してみた。
本家サイト
http://spekframework.org/
他の記事
http://qiita.com/yo1000/items/9f7148505895fd1d6760
http://qiita.com/tenten0213/items/95978e20e74a06e45a98
特徴
- テストの意図を明確にするように文章をテストコードに埋め込める
- デフォルトではJUnit5ベース
- Assersionライブラリは含まれないので色々なライブラリを選択可能(JUnit5と一緒ね)
今回やること
- いつのまにか追加されていたdata-driven-extensionを試す
- assertionライブラリとしては「kluent」を利用
https://markusamshove.github.io/Kluent/
build.gradle
group 'sample-kotlin'
version '1.0-SNAPSHOT'
buildscript {
ext.kotlin_version = '1.1.1'
repositories {
jcenter()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.0-M3'
}
}
repositories {
jcenter()
maven {
url "http://dl.bintray.com/kotlin/ktor"
}
maven { url "http://dl.bintray.com/jetbrains/spek" }
}
apply plugin: 'java'
apply plugin: 'kotlin'
apply plugin: 'org.junit.platform.gradle.plugin'
junitPlatform {
filters {
engines {
include 'spek'
}
}
platformVersion '1.0.0-M3'
}
sourceCompatibility = 1.8
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" //Kotlin
testCompile "org.junit.jupiter:junit-jupiter-api:5.0.0-M3"
testCompile 'org.jetbrains.spek:spek-api:1.1.0'
testCompile 'org.amshove.kluent:kluent:1.19'//アサーションライブラリ
testCompile 'org.jetbrains.spek:spek-junit-platform-engine:1.1.0'
testCompile 'org.jetbrains.spek:spek-data-driven-extension:1.1.0'//spekデータドリブンテスト用
}
テスト対象Function
sample.kt
package sample
fun add(x: Int, y: Int): Int = x + y
テストコード
sampletest.kt
package sample
//インポートは省略
class DataDrivenSpekTest : Spek({
describe("関数addは") {
on("%sと%sを加算した場合",
data(10,20, expected = 30),
data(-10,10, expected = 0)
) { a, b, expected ->
it("$expected を返却する") {
add(a, b) shouldEqualTo expected
}
}
}
})
結果

ちと改良
今の所、spek-data-driven-extensionは入力値、期待結果合わせて4列までのデータにしか対応していない。問題ない気もするが、もし、テストケースの説明なんかを入れたりして、5列以上のデータを扱いたいのならKotlinのdataclassと1.1からできるようになった分解宣言で対応すれば良い
sampletest2.kt
data class InputData(val x: Int, val y: Int) {
override fun toString() = "入力値[$x , $y]"
}
class DataDrivenSpekTest2 : Spek({
describe("関数addは") {
on("%s:%sを加算した場合",
data("基本条件",InputData(10,20), expected = 30),
data("負の数の計算",InputData(-10,10), expected = 0)
) { _,(a, b), expected ->
it("$expected を返却する") {
add(a, b) shouldEqualTo expected
}
}
}
})
