【问题标题】:Mockito ArgumentCaptor is Returning NullMockito ArgumentCaptor 返回 Null
【发布时间】:2013-08-13 00:46:57
【问题描述】:

我正在尝试使用 Mockito ArgumentCaptor 在我的方法中获取 mime 消息。当我取回捕获对象时,它的值为空。我很想调试它,但 Mockito 用增强器包装了它,所以我看不到内容。这适用于我的方法中的对象。有人有想法吗?

这是我的示例测试。 msg 不为 null,但之后调用的方法返回 null。

@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"));
}

【问题讨论】:

  • verify 调用中永远不需要times(1),因为这是verify 的默认值。
  • 我不知道,我是按照网上的一个例子来的。谢谢

标签: unit-testing junit mockito mime


【解决方案1】:

您已存根 createMimeMessage 以返回一个模拟。据推测,这个模拟是传递给send的;所以你的论点捕获者只是在捕捉模拟。模拟中的每个方法(getContentType() 和其他方法)都只是返回 null,因为您还没有对它们进行存根。

【讨论】:

  • 感谢您的回答和建议。您可能会注意到,我是 Mockito 的新手。谢谢,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-06
  • 1970-01-01
  • 2020-01-21
  • 1970-01-01
相关资源
最近更新 更多