2013-05-31 64 views
8

我有一個注入了JavaMailSender的服務。 我的服務配置它併發送郵件。 我想攔截原始郵件以確保信息是正確的。我想在JUnit中這樣做。如何測試Spring的JavaMailSender

你們會怎麼做?

@Service 
public class MyServiceImpl { 

    @Autowired 
    private JavaMailSender _mailSender; 

    public void sendMail(String to, String body, String subject){ 
     ... 
     _mailSender.something 
     ... 
    } 
} 

回答

4

您可以使用測試SMTP服務器,如Dumbster。看下面的例子:

@Test 
    public void sendSimpleEmailWithCC() { 
     // Runs a Dumbster simple SMTP server - default config 
     SimpleSmtpServer server = SimpleSmtpServer.start(); 
     String from = "[email protected]"; 
     String to = "[email protected]"; 
     String messageText = "Good message"; 
     String title = "Test message"; 
     String cc = "[email protected]"; 
     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)); 
    } 
+0

請不要使用啞鈴。這是可怕的打破: http://sourceforge.net/p/dumbster/bugs/15/。改用綠色郵箱。 –