Using Mockito doAnswer in Kotlin

what would be the Kotlin equivalent to this Java code?

doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        Design design = new Design();
        GetDesign.Listener callback = (GetDesign.Listener) invocation.getArguments()[0];
        callback.onSuccess(design);
        return null;
    }
}).when(someRepository).getDesign(any(GetDesign.Listener.class));

      

[UPDATE] After trying several options, I finally got it working using mockito-kotlin . I think the most convenient way to implement doAnswer

. The syntax remains largely unchanged:

doAnswer {
    callback = it.arguments[0] as GetDesign.Listener
    callback.onSuccess(Design())
    null
}.whenever(someRepository).execute(any(GetDesign.Listener::class.java))

      

Full code and build.gradle config can be found here

+11


source to share


2 answers


doAnswer {
    val design = Design()

    val callback = it.arguments[0] as GetDesign.Listener
    callback.onSuccess(design)

    null // or you can type return@doAnswer null

}.`when`(someRepository).getDesign(any(GetDesign.Listener::class.java))

      



+20


source


I'm a fan of the Full Mocking object, I don't want to load any config or any other dependency injection on load.

If I need to simulate the JavaMailSender function, I will do it like this. I will use theAnswer

to return the value.

Kotlin (just test JavaMailSender)

@Test
fun javaMailSenderTest(){
val jms = mock(JavaMailSender::class.java)
val mimeMessage = mock(MimeMessage::class.java)
mimeMessage.setFrom("no-reply@example.com")
mimeMessage.setText("Just a body text")

Mockito.'when'(jms.send(mimeMessage)).thenAnswer {
  // val callback = it.arguments[0]  <- Use these expression to get params values
  // Since JavaMailSender::send() function retrun void therefore, we should return Unit
  Unit
}

assertEquals(jms.send(mimeMessage), Unit)

      

}



Kotlin (using a custom class for JavaMailSender)

Chances are you can use your own Custom class to send mail, so here's what I did.

@Test
fun updateMembers&SendEmailTest() {

val mockEmailService= mock(MyEmailServiceImplementor::class.java)

// sendInfoMail(true|false) is my custom implemention of JavaMailSender
Mockito.'when'(mockEmailService.sendInfoMail(true)).thenAnswer { invocation ->
  Unit
}

assertEquals(mockEmailService.sendInfoMail(true), Unit)

      

}



Hope this helps someone. If you need Java version let me know in the comments

0


source







All Articles