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配置可以在这里找到
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))
我是Full Mocking对象的粉丝,我不想加载任何配置或任何其他弹簧启动依赖注入。
如果我必须模拟JavaMailSender函数,我会这样做。我将使用 theAnswer
返回值。
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 (使用 Java MailSender 的自定义类(
您可能正在使用自己的自定义类来发送邮件,所以我在这里完成了。
@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版本,请在注释中告诉我
现在你也可以做这样的事情(假设类型是Repository
(:
mock<Repository>() {
on { getDesign(any() as GetDesign.Listener) } doAnswer {
val callback = it.arguments[0] as GetDesign.Listener
callback.onSuccess(Design())
null
}
}