javascript
在Spring Boot应用程序中测试邮件代码
在構(gòu)建Spring Boot應(yīng)用程序時,您可能會需要添加郵件配置。 實際上,在Spring Boot中配置郵件與在Spring Bootless應(yīng)用程序中配置郵件沒有太大區(qū)別。 但是,如何測試郵件配置和提交工作正常? 我們來看一下。
我假設(shè)我們有一個引導(dǎo)的簡單Spring Boot應(yīng)用程序。 如果沒有,最簡單的方法是使用Spring Initializr 。
添加javax.mail依賴項
我們首先將javax.mail依賴項添加到build.gradle : compile 'javax.mail:mail:1.4.1' 。 我們還將需要包含JavaMailSender支持類的Spring Context Support (如果不存在)。 依賴項是: compile("org.springframework:spring-context-support")
基于Java的配置
Spring Boot支持基于Java的配置。 為了添加郵件配置,我們添加了帶有@Configuration注釋的MailConfiguration類。 這些屬性存儲在mail.properties (盡管不是必需的)。 可以使用@Value批注將屬性值直接注入到bean中:
@Configuration @PropertySource("classpath:mail.properties") public class MailConfiguration {@Value("${mail.protocol}")private String protocol;@Value("${mail.host}")private String host;@Value("${mail.port}")private int port;@Value("${mail.smtp.auth}")private boolean auth;@Value("${mail.smtp.starttls.enable}")private boolean starttls;@Value("${mail.from}")private String from;@Value("${mail.username}")private String username;@Value("${mail.password}")private String password;@Beanpublic JavaMailSender javaMailSender() {JavaMailSenderImpl mailSender = new JavaMailSenderImpl();Properties mailProperties = new Properties();mailProperties.put("mail.smtp.auth", auth);mailProperties.put("mail.smtp.starttls.enable", starttls);mailSender.setJavaMailProperties(mailProperties);mailSender.setHost(host);mailSender.setPort(port);mailSender.setProtocol(protocol);mailSender.setUsername(username);mailSender.setPassword(password);return mailSender;} }@PropertySource批注使mail.properties可用于通過@Value注入。 注解。 如果未完成,則可能會遇到異常: java.lang.IllegalArgumentException: Could not resolve placeholder '<name>' in string value "${<name>}" 。
和mail.properties :
mail.protocol=smtp mail.host=localhost mail.port=25 mail.smtp.auth=false mail.smtp.starttls.enable=false mail.from=me@localhost mail.username= mail.password=郵件端點
為了能夠在我們的應(yīng)用程序中發(fā)送電子郵件,我們可以創(chuàng)建一個REST端點。 我們可以使用Spring的SimpleMailMessage來快速實現(xiàn)此端點。 我們來看一下:
@RestController class MailSubmissionController {private final JavaMailSender javaMailSender;@AutowiredMailSubmissionController(JavaMailSender javaMailSender) {this.javaMailSender = javaMailSender;}@RequestMapping("/mail")@ResponseStatus(HttpStatus.CREATED)SimpleMailMessage send() { SimpleMailMessage mailMessage = new SimpleMailMessage();mailMessage.setTo("someone@localhost");mailMessage.setReplyTo("someone@localhost");mailMessage.setFrom("someone@localhost");mailMessage.setSubject("Lorem ipsum");mailMessage.setText("Lorem ipsum dolor sit amet [...]");javaMailSender.send(mailMessage);return mailMessage;} }運行應(yīng)用程序
現(xiàn)在,我們準(zhǔn)備運行該應(yīng)用程序。 如果使用CLI,請輸入: gradle bootRun ,打開瀏覽器并導(dǎo)航到localhost:8080/mail 。 您應(yīng)該看到的實際上是一個錯誤,表示郵件服務(wù)器連接失敗。 如預(yù)期的那樣。
偽造SMTP服務(wù)器
FakeSMTP是帶有Java的GUI的免費Fake SMTP服務(wù)器,用Java編寫,用于測試應(yīng)用程序中的電子郵件。 我們將使用它來驗證提交是否有效。 請下載該應(yīng)用程序,然后通過調(diào)用java -jar fakeSMTP-<version>.jar即可運行它。 啟動偽造的SMTP服務(wù)器后,啟動服務(wù)器。
現(xiàn)在,您可以再次調(diào)用REST端點,并在Fake SMTP中查看結(jié)果!
但是,測試并不是指手動測試! 該應(yīng)用程序仍然有用,但是我們要自動測試郵件代碼。
單元測試郵件代碼
為了能夠自動測試郵件提交,我們將使用Wiser –一種基于SubEtha SMTP的單元測試郵件的框架/實用程序。 SubEthaSMTP的簡單,低級API適用于編寫幾乎所有類型的郵件接收應(yīng)用程序。
使用Wiser非常簡單。 首先,我們需要向build.gradle添加一個測試依賴build.gradle : testCompile("org.subethamail:subethasmtp:3.1.7") 。 其次,我們使用JUnit,Spring和Wiser創(chuàng)建一個集成測試:
@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration public class MailSubmissionControllerTest {private Wiser wiser;@Autowiredprivate WebApplicationContext wac;private MockMvc mockMvc;@Beforepublic void setUp() throws Exception {wiser = new Wiser();wiser.start();mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();}@Afterpublic void tearDown() throws Exception {wiser.stop();}@Testpublic void send() throws Exception {// actmockMvc.perform(get("/mail")).andExpect(status().isCreated());// assertassertReceivedMessage(wiser).from("someone@localhosts").to("someone@localhost").withSubject("Lorem ipsum").withContent("Lorem ipsum dolor sit amet [...]");} }SMTP服務(wù)器進行初始化,開始@Before方法和停止@Teardown方法。 發(fā)送消息后,將進行斷言。 由于框架不提供任何斷言,因此需要創(chuàng)建斷言。 您將注意到,我們需要對Wiser對象進行操作,該對象提供了已接收消息的列表:
public class WiserAssertions {private final List<WiserMessage> messages;public static WiserAssertions assertReceivedMessage(Wiser wiser) {return new WiserAssertions(wiser.getMessages());}private WiserAssertions(List<WiserMessage> messages) {this.messages = messages;}public WiserAssertions from(String from) {findFirstOrElseThrow(m -> m.getEnvelopeSender().equals(from),assertionError("No message from [{0}] found!", from));return this;}public WiserAssertions to(String to) {findFirstOrElseThrow(m -> m.getEnvelopeReceiver().equals(to),assertionError("No message to [{0}] found!", to));return this;}public WiserAssertions withSubject(String subject) {Predicate<WiserMessage> predicate = m -> subject.equals(unchecked(getMimeMessage(m)::getSubject));findFirstOrElseThrow(predicate,assertionError("No message with subject [{0}] found!", subject));return this;}public WiserAssertions withContent(String content) {findFirstOrElseThrow(m -> {ThrowingSupplier<String> contentAsString = () -> ((String) getMimeMessage(m).getContent()).trim();return content.equals(unchecked(contentAsString));}, assertionError("No message with content [{0}] found!", content));return this;}private void findFirstOrElseThrow(Predicate<WiserMessage> predicate, Supplier<AssertionError> exceptionSupplier) {messages.stream().filter(predicate).findFirst().orElseThrow(exceptionSupplier);}private MimeMessage getMimeMessage(WiserMessage wiserMessage) {return unchecked(wiserMessage::getMimeMessage);}private static Supplier<AssertionError> assertionError(String errorMessage, String... args) {return () -> new AssertionError(MessageFormat.format(errorMessage, args));}public static <T> T unchecked(ThrowingSupplier<T> supplier) {try {return supplier.get();} catch (Throwable e) {throw new RuntimeException(e);}}interface ThrowingSupplier<T> {T get() throws Throwable;} }摘要
僅需幾行代碼,我們就可以自動測試郵件代碼。 本文介紹的示例并不復(fù)雜,但是它顯示了使用SubEtha SMTP和Wiser入門很容易。
您如何測試您的郵件代碼?
翻譯自: https://www.javacodegeeks.com/2014/09/testing-mail-code-in-spring-boot-application.html
總結(jié)
以上是生活随笔為你收集整理的在Spring Boot应用程序中测试邮件代码的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 六大银行是哪六大行?
- 下一篇: 农商银行智e付什么时候到帐?