【发布时间】:2017-07-11 14:59:28
【问题描述】:
我使用mockito 编写了以下单元测试来测试我的EmailService.java 类。我不确定我是否正确地测试了这个(快乐路径和异常情况)。
此外,我得到了这个Error: 'void' type not allowed here
在我的单元测试中的以下代码sn-p中
when(mockEmailService.notify(anyString())).thenThrow(MailException.class);
我知道,由于我的 notify() 方法返回 void,我得到了那个异常。但不知道如何解决这个问题。我的单元测试或实际课程或两者都需要更改代码吗?
谁能指导一下。
EmailServiceTest.java
public class EmailServiceTest {
@Rule
public MockitoJUnitRule rule = new MockitoJUnitRule(this);
@Mock
private MailSender mailSender;
@Mock
private EmailService mockEmailService;
private String emailRecipientAddress = "recipient@abc.com";
private String emailSenderAddress = "sender@abc.com";
private String messageBody = "Hello Message Body!!!";
@Test
public void testNotify() {
EmailService emailService = new EmailService(mailSender, emailRecipientAddress, emailSenderAddress);
emailService.notify(messageBody);
}
@Test(expected = MailException.class)
public void testNotifyMailException() {
when(mockEmailService.notify(anyString())).thenThrow(MailException.class);
EmailService emailService = new EmailService(mailSender, emailRecipientAddress, emailSenderAddress);
emailService.notify(messageBody);
}
}
EmailService.java
public class EmailService {
private static final Log LOG = LogFactory.getLog(EmailService.class);
private static final String EMAIL_SUBJECT = ":: Risk Assessment Job Summary Results::";
private final MailSender mailSender;
private final String emailRecipientAddress;
private final String emailSenderAddress;
public EmailService(MailSender mailSender, String emailRecipientAddress,
String emailSenderAddress) {
this.mailSender = mailSender;
this.emailRecipientAddress = emailRecipientAddress;
this.emailSenderAddress = emailSenderAddress;
}
public void notify(String messageBody) {
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject(EMAIL_SUBJECT);
message.setTo(emailRecipientAddress);
message.setFrom(emailSenderAddress);
message.setText(messageBody);
try {
mailSender.send(message);
} catch (MailException e) {
LOG.error("Error while sending notification email: ", e);
}
}
}
【问题讨论】:
-
道歉,复制粘贴问题。修复它
-
那么你的单元测试失败了吗?您收到什么错误消息?
-
第一个通过,第二个没有通过。根据 mockito,语法不正确。不确定我的生产代码是否需要返工或单元测试。请指导
标签: java unit-testing junit mockito