在Kotlin中使用Mockito doAnswer

x0fgdtte  于 2022-11-08  发布在  Kotlin
关注(0)|答案(3)|浏览(170)

这个Java代码的Kotlin等价物是什么

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]在尝试了几个选项之后,我最终使用mockito-kotlin使其工作。我认为这是实现doAnswer的最舒适的方式。语法几乎保持不变:

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

完整的代码和构建版本。gradle配置可以在here中找到

44u64gxh

44u64gxh1#

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

mrfwxfqh2#

我是Full Mocking对象的爱好者,我不想加载任何配置或任何其他启动依赖注入。
如果我必须模拟一个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的自定义类)

您可能会使用自己的自定义类来发送邮件,所以我在这里就这样做了。

@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版本,请在评论中告诉我

vs3odd8k

vs3odd8k3#

现在你也可以这样做(假设类型是Repository):

mock<Repository>() {
        on { getDesign(any() as GetDesign.Listener) } doAnswer {
            val callback = it.arguments[0] as GetDesign.Listener
            callback.onSuccess(Design())
            null
        }
    }

相关问题