1

We want to write tests for a project that uses Spring Boot and Spring AMQP. As we code in Kotlin we would like to use MockK instead of Mockito as it better fits Kotlin code style and best practices.

The RabbitListenerTestHarness class provides some convienient feature for testing @RabbitListeners. However, it returns implementations of Mockito's Answer interface, which are incompatible with the Answer interface of MockK.

Is there a way to use the Mockito answers with MockK, e.g. some exisiting wrappers for interoperability?

Consider the following example listener:

class SampleListener {
  @RabbitListener(id = "sampleReceiver", queues = ["testQueue"])
  fun receiveMessage(message: Message) {

  }
}

and the actual test:

@SpringBootTest
class SampleTest(@Autowired val template: TestRabbitTemplate) {
  @Autowired
  lateinit var testHarness: RabbitListenerTestHarness

  @Test
  fun testRabbit() {
    val spy = testHarness.getSpy<SampleListener>("sampleReceiver")
    val answer: LatchCountDownAndCallRealMethodAnswer = testHarness.getLatchAnswerFor("sampleReceiver", 1)

//    Mockito.doAnswer(answer).`when`(spy).receiveMessage(ArgumentMatchers.any())
    every { spy.receiveMessage(any()) } answers { /* what goes here? */ }

    template.convertAndSend("testQueue", "test")
  }
}

The test contains the Mockito call, as mentioned in the Docs, as comment. My question is, how can I use the answer object, returned from getLatchAnswerFor to complete the MockK stub?

Rosso
  • 428
  • 7
  • 17

1 Answers1

0

It's probably easier to not use the harness at all and add your own proxy around the message listener.

  • get the container from the RabbitListenerEndpointRegistry
  • get listener from the container, wrap it in a proxy and set it on the container
  • stop/start the container
  • send message(s)
Gary Russell
  • 166,535
  • 14
  • 146
  • 179
  • ... or don't use Mockk with it. I don't think that `every {}` is going to work with the Mockito spy (even if we can figure out how to delegate from the `answer {}`) since it is not created by the `mockk()` factory... – Artem Bilan Jan 10 '22 at 16:59
  • @ArtemBilan true, I didn't even think about that... Alright then, so we have to decide whether to use MockK and replace the harness with our own implementation or use Mockito for tests with the harness. Thank you for your insight – Rosso Jan 11 '22 at 08:38