LoginSignup
6
2

More than 5 years have passed since last update.

MockKでsuspend functionをモックした際にMockKExceptionが発生したのでメモ

Last updated at Posted at 2018-12-25

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


  1. 後から気づいたのですが、READMEには1.8.13.kotlin13がcurrentとしっかり書いてあるのでREADMEをとちゃんと読もう!という話だったりします。 

6
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2