2016-07-05 55 views
1

我想在春季測試我的服務,它應該發送電子郵件。 我嘗試使用org.subethamail:subethasmtp在春季測試發送郵件

要acieve我的目標,我創建服務MySender在那裏我發送電子郵件:

@Autowired 
private MailSender mailSender; 

//... 
    SimpleMailMessage message = new SimpleMailMessage(); 
    message.setTo("[email protected]"); 
    message.setSubject("Subject"); 
    message.setText("Text"); 
    mailSender.send(message); 
// ... 

爲了測試這一塊我創建的測試application.properties(測試範圍)代碼:

spring.mail.host=127.0.0.1 
spring.mail.port=${random.int[4000,6000]} 

和測試配置應啓動Wiser SMTP服務器並使其在測試中可重複使用的類:

@Configuration 
public class TestConfiguration { 

    @Autowired 
    private Wiser wiser; 

    @Value("${spring.mail.host}") 
    String smtpHost; 

    @Value("${spring.mail.port}") 
    int smtpPort; 

    @Bean 
    public Wiser provideWiser() { 
     // provide wiser for verification in tests 
     Wiser wiser = new Wiser(); 
     return wiser; 
    } 

    @PostConstruct 
    public void initializeMailServer() { 
     // start server 
     wiser.setHostname(smtpHost); 
     wiser.setPort(smtpPort); 
     wiser.start(); 
    } 

    @PreDestroy 
    public void shutdownMailServer() { 
     // stop server 
     wiser.stop(); 
    } 

} 

預期結果是應用程序使用Wiser smtp服務器發送電子郵件並驗證發送郵件的數量。

但是當我運行服務應用程序拋出MailSendException(Couldn't connect to host, port: 127.0.0.1, 4688; timeout -1;)。 但是,當我添加斷點並嘗試連接使用telnet smtp服務器允許連接,並不拋出Connection refused

你知道爲什麼我無法測試發送郵件嗎?

的完整代碼預覽可以在GitHub上: https://github.com/karolrynio/demo-mail

+0

在猜測,明智的服務器不是測試執行開始時完成。在運行測試之前,您可能需要在'@ Before'中執行某些操作以確保套接字處於活動狀態。 – Taylor

+0

我不確定,因爲在日誌中我有信息,服務器在測試日誌之前啓動,但我嘗試在運行測試之前等待服務器啓動。 – krynio

+1

我發現錯誤。我的問題的原因是配置。 Line:spring.mail.port = $ {random.int [4000,6000]},因爲spring將2個不同的值注入到bean中。 Bean MailSender具有與Wiser不同的端口值。謝謝你的幫助。 – krynio

回答

0

在應用程序屬性可以還添加

mail.smtp.auth=false 
mail.smtp.starttls.enable=false 

改變你的代碼,這些額外的兩個值

@Value("${mail.smtp.auth}") 
private boolean auth; 

@Value("${mail.smtp.starttls.enable}") 
private boolean starttls; 

並將這些選項放入您的initializeMailServer中

Properties mailProperties = new Properties(); 
mailProperties.put("mail.smtp.auth", auth); 
mailProperties.put("mail.smtp.starttls.enable", starttls); 
wiser.setJavaMailProperties(mailProperties); 
wiser.setHostname(smtpHost); 
wiser.setPort(smtpPort); 
wiser.start(); 

讓我知道如果這個工作對你

+0

我稍後檢查。謝謝。 – krynio

+0

它不起作用,但我發現其他庫用於測試發送電子郵件,我試了一下。 – krynio

+0

那個庫是什麼 – rajadilipkolli