在Kotlin使用Mockito doAnswer

时间:2017-05-19 09:58:30

标签: testing mockito kotlin

Kotlin与这个Java代码相当的是什么?

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));

[更新]尝试了几个选项后,我终于使用mockito-kotlin使其工作了。我认为这是实施doAnswer最舒适的方式。语法几乎保持不变:

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

可以找到完整的代码和build.gradle配置here

2 个答案:

答案 0 :(得分:17)

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))

答案 1 :(得分:0)

我是Full Mocking对象的粉丝,我不想加载任何配置或任何其他spring boot依赖项注入。

如果我必须模拟JavaMailSender函数,我将这样做。我将使用theAnswer返回值。

Kotlin(只需测试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(为JavaMailSender使用自定义类)

可能您正在使用自己的Custom类来发送邮件,所以我在这里做了。

@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)

}

希望这对某人有帮助。如果您需要Java版本,请在评论中告诉我