io.mockk.MockKException:未找到答案:SavedStateHandle(#1).set(Key, Something)
io.mockk.MockKException: no answer found for: SavedStateHandle(#1).set(Key, Something)
我有一个 ViewModel class 如下(简化以演示我遇到的问题)
class MyViewModel(private val savedStateHandle: SavedStateHandle) : ViewModel() {
init {
savedStateHandle.set(KEY, "Something")
}
}
我有一个 MockK 测试 class 如下
@Test
fun `test something simple`() {
val savedStateHandle = mockk<SavedStateHandle>()
val viewModel = MyViewModel(savedStateHandle)
verify { savedStateHandle.set(MyViewModel.KEY, "Something") }
}
通过运行测试我得到以下错误
io.mockk.MockKException: no answer found for: SavedStateHandle(#1).set(Key, Something)
我想我还需要为 SavedStateHandle
处理 set
。我怎么能在 MockK
中这样做?
看来我需要 relaxed = true
到我的 Mock,使其成为 return 默认值。
@Test
fun `test something simple`() {
val savedStateHandle = mockk<SavedStateHandle>(relaxed = true)
val viewModel = MyViewModel(savedStateHandle)
verify { savedStateHandle.set(MyViewModel.KEY, "Something") }
}
另一种选择是模拟 return 值...
@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") }
}
我有一个 ViewModel class 如下(简化以演示我遇到的问题)
class MyViewModel(private val savedStateHandle: SavedStateHandle) : ViewModel() {
init {
savedStateHandle.set(KEY, "Something")
}
}
我有一个 MockK 测试 class 如下
@Test
fun `test something simple`() {
val savedStateHandle = mockk<SavedStateHandle>()
val viewModel = MyViewModel(savedStateHandle)
verify { savedStateHandle.set(MyViewModel.KEY, "Something") }
}
通过运行测试我得到以下错误
io.mockk.MockKException: no answer found for: SavedStateHandle(#1).set(Key, Something)
我想我还需要为 SavedStateHandle
处理 set
。我怎么能在 MockK
中这样做?
看来我需要 relaxed = true
到我的 Mock,使其成为 return 默认值。
@Test
fun `test something simple`() {
val savedStateHandle = mockk<SavedStateHandle>(relaxed = true)
val viewModel = MyViewModel(savedStateHandle)
verify { savedStateHandle.set(MyViewModel.KEY, "Something") }
}
另一种选择是模拟 return 值...
@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") }
}