模拟MIMEMessage的正确方法?

时间:2018-10-31 21:04:56

标签: java mockito javamail mime

我实际上想验证消息上设置的字段,例如正文,主题,来源等...我也尝试过进行参数捕获,但这种方法不起作用,并且在调试代码时,消息是当它获得javaMailSender.send(message)行时,总是显示空字段。

模拟MIMEMessage是否有最佳实践?

//EmailService.java

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Slf4j
public class EmailService {
    private JavaMailSender javaMailSender;

    @Autowired
    public EmailService(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }


    public void sendEmail() {
        MimeMessage message = javaMailSender.createMimeMessage();
        String body = "<html>\n" +
            "<p> This the body </p>\n" +
            "<br>\n";
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message, true);
            mimeMessageHelper.setSubject("subject");
            mimeMessageHelper.setTo("stack@overflow.com");
            mimeMessageHelper.setFrom("overflow@stack.com");
            mimeMessageHelper.setText(body, true);

            javaMailSender.send(message);

        } catch (MessagingException e) {
            log.error("error");
        }`enter code here`
    }
}

下面是测试

//EmailServiceTest.java

import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.springframework.mail.javamail.JavaMailSender;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;


public class EmailServiceTest {
    private EmailService emailService;

    @Mock
    private JavaMailSender javaMailSender;

    @Mock
    private MimeMessage message;

    @Before
    public void setUp() throws IOException {
        initMocks(this);

        emailService = new EmailService(javaMailSender);
    }

    @Test
    public void sendEmail_sendsEmailWithCorrectContent() throws MessagingException {
        ArgumentCaptor<MimeMessage> mimeMessageArgumentCaptor = ArgumentCaptor.forClass(MimeMessage.class);
        when(javaMailSender.createMimeMessage()).thenReturn(message);

        doNothing().when(javaMailSender).send(message);

        emailService.sendEmail();

        verify(javaMailSender, times(1)).send((mimeMessageArgumentCaptor.capture()));
        assertEquals("subject", mimeMessageArgumentCaptor.getValue().getSubject());
    }

}

1 个答案:

答案 0 :(得分:3)

进行这种测试using an integration test通常比较容易。电子邮件通常是使用诸如freemarker之类的模板库构建的,因此集成测试对于能够验证模板是否正确也很有价值。

您可以使用PowerMock创建模拟MimeMessageHelper来进行单元测试,但是PowerMock有时会跟不上对其他测试库的更改,因此这种测试常常会变得很脆弱,而且价值不大。例如,您可以验证是否在setSubject()上调用了mimeMessageHelper,但是会产生您真正想要测试的结果(主题设置在message上)吗?