我有一个已注入JavaMailSender的服务。 我的服务配置它并发送邮件。 我想截取原始邮件以确保信息正确无误。我想在JUnit中这样做。
你们会怎么做?
@Service
public class MyServiceImpl {
@Autowired
private JavaMailSender _mailSender;
public void sendMail(String to, String body, String subject){
...
_mailSender.something
...
}
}
答案 0 :(得分:22)
我是使用GreenMail完成的。看看my blog post about it,你也可以找到一个有效的例子。
答案 1 :(得分:5)
您可以使用测试SMTP服务器,例如Dumbster。请参阅以下示例:
@Test
public void sendSimpleEmailWithCC() {
// Runs a Dumbster simple SMTP server - default config
SimpleSmtpServer server = SimpleSmtpServer.start();
String from = "whoever@from.com";
String to = "whoever@to.com";
String messageText = "Good message";
String title = "Test message";
String cc = "whoever@cc.com";
Assert.assertTrue(mailSender
.sendEmail(from, to, cc, title, messageText));
server.stop();
Assert.assertTrue(server.getReceivedEmailSize() == 1);
Iterator emailIter = server.getReceivedEmail();
SmtpMessage email = (SmtpMessage) emailIter.next();
Assert.assertTrue(email.getHeaderValue("From").equals(from));
Assert.assertTrue(email.getHeaderValue("To").equals(to));
Assert.assertTrue(email.getHeaderValue("Cc").equals(cc));
Assert.assertTrue(email.getHeaderValue("Subject")
.equals("Test message"));
Assert.assertTrue(email.getBody().equals(messageText));
}
答案 2 :(得分:0)
如果您的目标是仅使用Junit / Mockito并在发送之前测试MimeMessage的形成方式,则以下配置应足够:
public class EmailServiceTest {
private EmailServiceImpl emailServiceImpl;
private JavaMailSender javaMailSender;
private MimeMessage mimeMessage;
@Before
public void before() {
mimeMessage = new MimeMessage((Session)null);
javaMailSender = mock(JavaMailSender.class);
when(javaMailSender.createMimeMessage()).thenReturn(mimeMessage);
emailServiceImpl = new EmailService(javaMailSender);
}
@Test
public void emailTest() {
String recipient = "example@example.com"
EmailRequest request = new EmailRequest();
request.setRecipient(recipient);
emailServiceImpl.send(request);
assertEquals(recipient, mimeMessage.getRecipients(RecipientType.TO)[0].toString());
}
}