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")
}
}
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)
I guess I need to handle the set
for SavedStateHandle
as well. How could I do so in MockK
?
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") }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With