2
ContactDTO cDto = new ContactDTO();
cDto.setTitle("Mr");
cDto.setFirstName("Pritam");
cDto.setLastName("Mohapatra");
cDto.setTelephone("9439586575");
cDto.setEmail("pritam.pritam176@gmail.com");
cDto.setBetreff("test value");
cDto.setAnfrage("test value");

MessageTemplate messageTemplate=new MessageTemplate();
messageTemplate.setBody("Hallo ${name}.<br><br> want to contact ");
messageTemplate.setSubject("Refernce email");
when(emailProperties.getContactMsgKey()).thenReturn("4");
String key = "4";
when(messageTemplateService.getMessageTemplateById(key)).thenReturn(messageTemplate);
when(emailProperties.getAdminTo()).thenReturn("admin@gmail.com");

//String key = "3";
//when(messageTemplateService.getMessageTemplateById(key)).thenReturn(messageTemplate);
String to=emailProperties.getAdminTo();
String subject =messageTemplate.getSubject();
String body =messageTemplate.getBody().replace("${name}", cDto.getFirstName());
String contentType="text/html";
doThrow(NullPointerException.class).when(emailService).sendEmail(to, subject, body, contentType);
emailService.sendEmail(to, subject, body, contentType);

我在运行 JUnit 测试时收到 NullPointerException。我究竟做错了什么?
我正在使用它来发送电子邮件。

@Before
public void init() {

    emailService = mock(EmailServiceImpl.class);
    messageTemplateService =mock(MessageTemplateService.class);
    emailProperties=mock(EmailProperties.class);

    emailService.setEmailProperties(emailProperties);
    emailService.setMessageTemplateService(messageTemplateService);

}
  • 这是我的@before 方法:
4

1 回答 1

1

我认为您触发自己的NullPointerException原因是:

doThrow(NullPointerException.class).when(emailService).sendEmail(to, subject, body, contentType);

该指令告诉 MockitoNullPointerException 在您调用sendEmail方法时抛出 a ,emailService这就是您在调用之后直接执行的操作:

emailService.sendEmail(to, subject, body, contentType);
于 2015-03-31T10:07:28.830 回答