facebook twitter hatena line email

「Android/kotlin/UnitTest/mockk」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(試験対象を準備)
 
行30: 行30:
 
出力
 
出力
 
  I/System.out: Car().drive()=going faster
 
  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を返す判断とする場合==
 
==voidを返す判断とする場合==

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 [ショートカット]