【问题标题】:MockK: no answer found because the mock is modified from outsideMockK:找不到答案,因为模拟是从外部修改的
【发布时间】:2021-02-22 12:18:09
【问题描述】:

各位开发者您好,

我有以下问题:

假设我有一个名为 UseCaseX 的类:

class UseCaseX (private val repository: Repository) {

    override suspend fun invoke(params: Unit?) = repository.call()

}

现在,这个 UseCaseX 在类 ViewModel 中使用,如下所示:

    ...
    val result = async { useCaseX.invoke(null) }
    ...

然后我使用 MockK 在 ViewModelTest 中模拟 UseCaseX,如下所示:

val useCaseX = mockk<UseCaseX>(relaxUnitFun = true)

我收到以下错误:

io.mockk.MockKException: no answer found for: UseCaseX(#7).invoke(null, continuation {})
at io.mockk.impl.stub.MockKStub.defaultAnswer(MockKStub.kt:90)
at io.mockk.impl.stub.MockKStub.answer(MockKStub.kt:42)

显然UseCaseX.invoke(params) 函数在async{} 期间通过附加参数进行了扩展,但到目前为止还没有答案。

问题:在这种情况下如何为模拟提供答案?

【问题讨论】:

    标签: unit-testing kotlin junit mocking mockk


    【解决方案1】:

    使用withContext(Dispatchers.Default) 而不是async。应该可以!

    【讨论】:

      猜你喜欢
      • 2022-01-17
      • 1970-01-01
      • 2019-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-05
      • 2019-06-18
      • 1970-01-01
      相关资源
      最近更新 更多