「Android/kotlin/UnitTest/mockk」の版間の差分
提供: 初心者エンジニアの簡易メモ
(ページの作成:「==mockk== kotlin網羅したモック 公式:https://mockk.io/#installation ==設定== app/build.gradle <pre> dependencies { testImplementation 'io.mockk:mockk:1....」) |
(→試験対象を準備) |
||
| (同じ利用者による、間の8版が非表示) | |||
| 行3: | 行3: | ||
公式:https://mockk.io/#installation | 公式:https://mockk.io/#installation | ||
| + | |||
| + | 使い方 https://qiita.com/yasuX/items/d3cfc9853c53dfaee222 | ||
==設定== | ==設定== | ||
| 行11: | 行13: | ||
} | } | ||
</pre> | </pre> | ||
| + | |||
| + | ==試験対象を準備== | ||
| + | Car.kt | ||
| + | <pre> | ||
| + | class Car { | ||
| + | fun drive() = accelerate() | ||
| + | |||
| + | private fun accelerate() = "going faster" | ||
| + | } | ||
| + | </pre> | ||
| + | |||
| + | MainActivity.kt | ||
| + | <pre> | ||
| + | println("Car().drive()=" + Car().drive()) | ||
| + | </pre> | ||
| + | 出力 | ||
| + | I/System.out: Car().drive()=going faster | ||
| + | |||
| + | ==サンプル== | ||
| + | <pre> | ||
| + | package com.example.unittestapplication | ||
| + | |||
| + | import kotlinx.coroutines.runBlocking | ||
| + | import org.junit.Test | ||
| + | |||
| + | import org.junit.Assert.* | ||
| + | import com.google.common.truth.Truth.assertThat | ||
| + | |||
| + | class ExampleUnitTest { | ||
| + | @Test | ||
| + | fun car_drive() { | ||
| + | var actual = Car().drive() | ||
| + | var expected = "going faster" | ||
| + | assertThat(actual).isEqualTo(expected) | ||
| + | } | ||
| + | } | ||
| + | </pre> | ||
| + | |||
| + | ==voidを返す判断とする場合== | ||
| + | Unitを返せば良い。 | ||
| + | |||
| + | ==実行確認== | ||
| + | *everyは、戻り値有り | ||
| + | *verifyは、戻り値なし | ||
| + | *coEveryは、suspendを使ったfunで、戻り値有り | ||
| + | *coVerifyは、suspendを使ったfunで、戻り値なし | ||
| + | |||
| + | ==AssertThatが使えない場合== | ||
| + | [[Android/kotlin/UnitTest/AssertThat]] [ショートカット] | ||
2021年2月20日 (土) 08:32時点における最新版
mockk
kotlin網羅したモック
公式:https://mockk.io/#installation
使い方 https://qiita.com/yasuX/items/d3cfc9853c53dfaee222
設定
app/build.gradle
dependencies {
testImplementation 'io.mockk:mockk:1.10.4'
}
試験対象を準備
Car.kt
class Car {
fun drive() = accelerate()
private fun accelerate() = "going faster"
}
MainActivity.kt
println("Car().drive()=" + Car().drive())
出力
I/System.out: Car().drive()=going faster
サンプル
package com.example.unittestapplication
import kotlinx.coroutines.runBlocking
import org.junit.Test
import org.junit.Assert.*
import com.google.common.truth.Truth.assertThat
class ExampleUnitTest {
@Test
fun car_drive() {
var actual = Car().drive()
var expected = "going faster"
assertThat(actual).isEqualTo(expected)
}
}
voidを返す判断とする場合
Unitを返せば良い。
実行確認
- everyは、戻り値有り
- verifyは、戻り値なし
- coEveryは、suspendを使ったfunで、戻り値有り
- coVerifyは、suspendを使ったfunで、戻り値なし
AssertThatが使えない場合
Android/kotlin/UnitTest/AssertThat [ショートカット]
