4

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.

Naruto Sempai
  • 6,233
  • 8
  • 35
  • 51
  • 1
    On one hand, nice job in figuring it out! But some food for thought: Perhaps mocking how you parse a Json might not be the best practice for your use case. Create fake jsons instead of mocking object mapper itself, and that will probably improve your test codebase – LeoColman Aug 24 '20 at 04:23
  • 2
    I am taking your suggestion to heart and will consider what you say. I've created a toy example of course, but in the actual code base in this _particular_ test it would have been easier to point out how I am less concerned with the json's exact content. But that doesn't discount that you still maybe correct in terms of an overall strategy. – Naruto Sempai Aug 24 '20 at 17:31

1 Answers1

3

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
    ...
}
Naruto Sempai
  • 6,233
  • 8
  • 35
  • 51