使用Spock时我可以这样做:
when:
12.times {mailSender.send("blabla", "subject", "content")}
then:
12 * javaMailSender.send(_)
当我试图在Mockito中做同样的事情时:
verify(javaMailSender,times(12)).send(any(SimpleMailMessage.class))
我收到一个错误,SimpleMailMessage有空值,所以我不得不在test中初始化它:
SimpleMailMessage simpleMailMessage = new SimpleMailMessage()
simpleMailMessage.setTo("blablabla")
simpleMailMessage.subject = "subject"
simpleMailMessage.text = "content"
verify(javaMailSender,times(12)).send(simpleMailMessage))
现在它有效,但是工作量很大,我真的不关心平等。如果SimpleMailMessage将拥有更多参数或具有其他参数的其他对象,那么该怎么办呢。有没有办法检查send方法只被调用了X次?
编辑:添加了send方法的实现。
private fun sendEmail(recipient: String, subject: String, content: String)
{
val mailMessage = SimpleMailMessage()
mailMessage.setTo(recipient)
mailMessage.subject = subject
mailMessage.text = content
javaMailSender.send(mailMessage)
}
有2个发件人,mailSender是我的自定义对象,而javaMailSender来自另一个libary
堆栈跟踪:
Mockito.verify(javaMailSender,
Mockito.times(2)).send(Mockito.any(SimpleMailMessage.class))
| | | | |
| | | | null
| | | Wanted but not invoked:
| | | javaMailSender.send(
| | | <any org.springframework.mail.SimpleMailMessage>
| | | );
| | | -> at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
| | |
| | | However, there were exactly 2 interactions with this mock:
| | | javaMailSender.send(
| | | SimpleMailMessage: from=null; replyTo=null; to=blabla; cc=; bcc=; sentDate=null; subject=subject; text=content
| | | );
| | | -> at MailSenderServiceImpl.sendEmail(MailSenderServiceImpl.kt:42)
| | |
| | | javaMailSender.send(
| | | SimpleMailMessage: from=null; replyTo=null; to=blabla; cc=; bcc=; sentDate=null; subject=subject; text=content
| | | );
答案 0 :(得分:0)
如果您不关心send的参数,请将any()留空:
verify(javaMailSender,times(12)).send(any())