MockKはKotlinフレンドリーなMockingライブラリです。特徴はこちらにまとめられていますが、その一つにmocking coroutines
があげられています。
suspend functionのmocking
MockKを利用することでsuspend functionについても簡単にモックを作成できます。例えば次のようなinterfaceが定義されていて、Result型を返すとします。
sealed class Result {
data class Success(val value: String) : Result()
data class Failure(val exception: Exception) : Result()
}
interface UseCase {
suspend fun execute(): Result
}
この場合次のようにモックを作成し、coEvery
を使用することでsuspend functionであるexecute
の戻り値を明示的に指定できます。
val mock: UseCase = mockk {
coEvery { execute() } returns Result.Success("success")
}
io.mockk.MockKException: Add coroutines support artifact…
coEvery
を使用したテストを実行すると次のようなエラーが表示されテストが失敗します。
io.mockk.MockKException: Add coroutines support artifact 'org.jetbrains.kotlinx:kotlinx-coroutines-core' to your project
Add coroutines support artifact 'org.jetbrains.kotlinx:kotlinx-coroutines-core' to your project
とありますが、既にプロジェクトに追加済みの場合でもこのエラーは発生します。
対処方法
MockKのバージョンに1.8.13.kotlin13
を指定することで上記の問題を回避できます。dependencies
での定義は次のようになります。
testImplementation 'io.mockk:mockk:1.8.13.kotlin13'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.0.1'
こちらのissueを見つけて無事解決できました。1
-
後から気づいたのですが、READMEには
1.8.13.kotlin13
がcurrentとしっかり書いてあるのでREADMEをとちゃんと読もう!という話だったりします。 ↩