本文介绍了io.mockk.MockKException:找不到以下答案:SavedStateHandle(#1).set(Key,Something)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下的ViewModel类(简化以演示我遇到的问题)

I have a ViewModel class as below (simplified to demonstrate the problem I faced)

class MyViewModel(private val savedStateHandle: SavedStateHandle) : ViewModel() {
    init {
        savedStateHandle.set(KEY, "Something")
    }
}

我有一个如下的MockK测试班

I have a MockK testing class as below

@Test
fun `test something simple`() {
    val savedStateHandle = mockk<SavedStateHandle>()
    val viewModel = MyViewModel(savedStateHandle)
    verify { savedStateHandle.set(MyViewModel.KEY, "Something") }
}

通过运行测试,我得到以下错误

By running the test I get the below error

io.mockk.MockKException: no answer found for: SavedStateHandle(#1).set(Key, Something)

我想我也需要处理SavedStateHandleset.如何在MockK中这样做?

I guess I need to handle the set for SavedStateHandle as well. How could I do so in MockK?

推荐答案

好像我需要relaxed = true到我的Mock,使其只返回默认值.

Looks like I need to relaxed = true to my Mock, to make it just return a default value.

@Test
fun `test something simple`() {
    val savedStateHandle = mockk<SavedStateHandle>(relaxed = true)
    val viewModel = MyViewModel(savedStateHandle)
    verify { savedStateHandle.set(MyViewModel.KEY, "Something") }
}

另一个选择是模拟返回值...

The other option is to mock the return value...

@Test
fun `test something simple`() {
    val savedStateHandle = mockk<SavedStateHandle>()
    every {savedStateHandle.set(MyViewModel.KEY, "Something") } returns Unit
    val viewModel = MyViewModel(savedStateHandle)
    verify { savedStateHandle.set(MyViewModel.KEY, "Something") }
}

这篇关于io.mockk.MockKException:找不到以下答案:SavedStateHandle(#1).set(Key,Something)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 00:38