Я хочу на самом деле проверить поля, установленные в сообщении, такие как тело, тема, от и т.д. всегда показывает пустые поля, когда получает строку 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());
}
}