2016-06-28 186 views
0

請幫我寫一個電子郵件發送的集成測試,inreal發送電子郵件。電子郵件發送集成測試

public interface MailSenderService { 

void sendEmail(String to, String from, String subject, String body); } 

郵件發件人類

@Service 
public class MailSenderServiceImpl implements MailSenderService { 
private static final Logger logger = LoggerFactory.getLogger(MailSenderServiceImpl.class); 

@Autowired 
private JavaMailSender javaMailSender; 

@Autowired 
Configuration freemarkerConfiguration; 

private SimpleMailMessage composeMail(String to, String from, String subject, String body) { 
    SimpleMailMessage message = new SimpleMailMessage(); 
    message.setFrom(from); 
    message.setTo(to); 
    message.setSubject(subject); 
    message.setText(body); 
    return message; 
} 

@Override 
public void sendEmail(String to, String from, String subject, String body) { 
    sendMessage(composeMail(to, from, subject, body)); 
} 

@Async 
private void sendMessage(SimpleMailMessage message) { 
    Assert.notNull(javaMailSender, "Email Sender must not be null"); 
    javaMailSender.send(message); 
}} 

最後這裏是一個集成測試,其不通過:

public class MailSenderServiceIT extends BaseServiceIntegrationTest { 

@Autowired 
private MailSenderService mailSenderService; 

@Test 
public void sendEmail() { 
    mailSenderService.sendEmail("[email protected]", "[email protected]", "Test Subject", 
      "Test Body"); 
    flushAndClear(); 
} 

回答

0

我們需要知道如何配置你的JavaMailSender。如果您想在集成測試中發送電子郵件,則需要配置JavaMailSender以使用本地配置。舉例本地主機:5555:

JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl(); 
javaMailSender.setHost("localhost"); 
javaMailSender.setPort(5555); 

然後,您可以在您的測試使用庫subethasmtp直接創建一個SMTP服務器。我personnaly創建JUnit規則做到這一點:

public class SMTPServerRule extends ExternalResource { 

    private Wiser wiser; 
    private String hostname; 
    private int port; 

    public SMTPServerRule() { 
     this(25); 
    } 

    public SMTPServerRule(int port) { 
     this("localhost", port); 
    } 

    public SMTPServerRule(String hostname, int port) { 
     this.hostname = hostname; 
     this.port = port; 
    } 


    @Override 
    protected void before() throws Throwable { 
     super.before(); 

     wiser = new Wiser(port); 
     wiser.setHostname(hostname); 
     wiser.start(); 
    } 

    public List<WiserMessage> getMessages() { 
     return wiser.getMessages(); 
    } 

    @Override 
    protected void after() { 
     super.after(); 
     wiser.stop(); 
    } 
} 

所以,你可以做這樣的事情在你的集成測試:

@Rule 
public SMTPServerRule smtpServerRule = new SMTPServerRule("localhost", 5555); 

@Test 
public void sendEmail() { 
    mailSenderService.sendEmail("[email protected]", "[email protected]", "Test Subject", "Test Body"); 
    flushAndClear(); 

    List<WiserMessage> messages smtpServerRule.getMessages(); 
} 
+0

我使用這些屬性的郵件發送: smtp.host = SMTP .gmail.com smtp.port = 587 [email protected] smtp.password = aaa12345678 $ – Mary

+0

運行測試我收到MailAuthenticationException – Mary