Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 553
Elye Avatar asked Apr 11 '20 03:04

Elye


1 Answers

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") }
}
like image 176
Elye Avatar answered Nov 14 '22 16:11

Elye