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);

I am getting NullPointerException on Running JUnit Test. What am I doing wrong?
I am using this for email sending.

@Before
public void init() {

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

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

}
  • here is my @before method:
Grzegorz Piwowarek
  • 13,172
  • 8
  • 62
  • 93
  • 1
    Maybe you should see and post the stacktrace as well :) It usually helps – shikjohari Mar 31 '15 at 06:19
  • where you initialize emailProperties and emailService ? – hudi Mar 31 '15 at 06:32
  • sorry I add the code. – PRITAM MOHAPATRA Mar 31 '15 at 07:00
  • The stack trace tells you exactly in which line of your code the exception happens. Please look at the stack trace to find out where exactly it happens. You might need to do more with your mocks, if you just create a mock without any behaviour the mock will probably return `null` when calling its methods, causing a NPE. – Jesper Mar 31 '15 at 10:04
  • Using your actual contact details in the code snippet doesn't look like a good idea to me. – ankon Mar 31 '15 at 10:05

1 Answers1

1

I think you triger yourself the NullPointerException because of:

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

This instruction tells Mockito to throw a NullPointerException when you call the sendEmail method on the emailService which is what you do directly after by calling:

emailService.sendEmail(to, subject, body, contentType);
Xavier Delamotte
  • 3,519
  • 19
  • 30