Question

I am trying to use Mockito ArgumentCaptor to get the mime message in my method. When I get the capture object back its values are null. I tyro to debug it, but Mockito wraps it with an enhancer, so I cannot see the contents. That applies to the objects in my method. Does anyone have an idea?

Here is my sample test. msg is not null, but the method calls after that return nulls.

@Test
public void testSendTemplatedMail() throws MessagingException, IOException {
    Context ctx = new Context();
    ctx.setVariable("name", "John Doe");
    ctx.setVariable("subscriptionDate", new Date());
    ctx.setVariable("hobbies", Arrays.asList("Cinema", "Sports", "Music"));
    String templateName = "testEmailTemplateWithoutImage";
    when(mailSenderMock.createMimeMessage()).thenReturn(mock(MimeMessage.class));

    try {
        mailUtils.sendTemplatedMail("John Doe", "john.doe@bbc.com",
                        "no-reply@leanvelocitylabs.com", "Hello",
                        templateName, ctx);
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }

    ArgumentCaptor<MimeMessage> msg = ArgumentCaptor.forClass(MimeMessage.class);

    verify(mailSenderMock, times(1)).createMimeMessage();
    verify(mailSenderMock, times(1)).send(msg.capture());
    verifyNoMoreInteractions(mailSenderMock);

    System.out.println("Sample msg subject = " + msg);
    System.out.println("Sample msg ctype = " + msg.getValue().getContentType());
    System.out.println("Sample msg to = " + msg.getValue().getAllRecipients());
    System.out.println("Sample msg sender = " + msg.getValue().getSender());
    System.out.println("Sample msg from = " + msg.getValue().getFrom());
    System.out.println("Sample msg content = " + msg.getValue().getContent());




    // assertEquals("accountAlmostDone", mv.getViewName());
    // assertEquals("NA", mv.getModel().get("activationCode"));
}
Was it helpful?

Solution

You've stubbed createMimeMessage to return a mock. Presumably, this mock is what is being passed to send; so your argument captor is just capturing the mock. Each of the methods on the mock (getContentType() and the others) is just returning null, because you haven't stubbed them yet.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top