DoThrow MailException 与 mockito

DoThrow MailException with mockito

我有一个 class JavaMailDao,我想使用 JUnit 和 mockito 对其进行测试。我想测试Catch部分

try {
            this.mailSender.send(msg);
    } catch(MailException ex) {
            throw new BackendException(DaoExceptionType.EMAIL_ERROR);
}

在测试中我有这个:

Mockito.doNothing().doThrow(new MailException()).when(this.mailSenderMock).send(Mockito.any(SimpleMailMessage.class));

它说的问题是:"can't instantiate the type MailException",顺便说一句,我也有导入。

mport org.springframework.mail.MailException;

有人知道怎么做吗?谢谢!

MailException 是一个摘要 class。抽象classes无法实例化,所以实例化其中一个子classes,如MailSendException.

解决方案:

Mockito.doNothing().doThrow(new MailSendException("Test message")).when(this.mailSenderMock).send(Mockito.any(SimpleMailMessage.class));`

请参阅 the Spring Framework docs 了解更多信息和合适的子classes。