Naruto Sempai
Naruto Sempai

Reputation: 7201

io.mockk.MockKException: no answer found when mocking list of objects with ObjectMapper.readValue() using mockk?

There were similar questions but none dealing specifically with kotlin, mockk and using objectMapper.readValue to read a list of objects.

Given a method:

fun someMethod(message: Message): List<Animal> = objectMapper.readValue(
        String(message.body),
        object : TypeReference<List<Animal>>() {}
)

I tried to mock it here:

@Test
fun `test you filthy animals`() {
    ...
    val animals: List<Animal> = emptyList()
    every { objectMapper.readValue<List<Animal>>(
       any<String>(), 
       any<Class<List<Animal>>>()
    ) } returns animals
    ...
}

But that didn't work. I got the following error:

io.mockk.MockKException: no answer found for: ObjectMapper(#72).readValue(
     somebody,  
     be.kind.to.Nature$someMethod$animals$1@46b2a11a
)

halp.

Upvotes: 5

Views: 2833

Answers (1)

Naruto Sempai
Naruto Sempai

Reputation: 7201

Took me forever to work through this but sharing it here for prosperity!

@Test
fun `test you filthy animals`() {
    ...
    val animals: List<Animal> = emptyList()
    every { objectMapper.readValue<List<Animal>>(
       any<String>(), 
       any<TypeReference<List<Animal>>>()
    ) } returns animals
    ...
}

Upvotes: 4

Related Questions