在构建Spring Boot应用程序时,您可能会需要添加邮件配置。 实际上,在Spring Boot中配置邮件与在Spring Bootless应用程序中配置邮件没有太大区别。 但是,如何测试邮件配置和提交工作正常? 我们来看一下。

我假设我们有一个引导的简单Spring Boot应用程序。 如果没有,最简单的方法是使用Spring Initializr 。

添加javax.mail依赖项

我们首先将javax.mail依赖项添加到build.gradlecompile '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=

邮件端点

为了能够在我们的应用程序中发送电子邮件,我们可以创建一个REST端点。 我们可以使用Spring的SimpleMailMessage来快速实现此端点。 我们来看一下:

@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;}
}

运行应用程序

现在,我们准备运行该应用程序。 如果使用CLI,请输入: gradle bootRun ,打开浏览器并导航到localhost:8080/mail 。 您应该看到的实际上是一个错误,表示邮件服务器连接失败。 如预期的那样。

伪造SMTP服务器

FakeSMTP是带有Java的GUI的免费Fake SMTP服务器,用Java编写,用于测试应用程序中的电子邮件。 我们将使用它来验证提交是否有效。 请下载该应用程序,然后通过调用java -jar fakeSMTP-<version>.jar即可运行它。 启动伪造的SMTP服务器后,启动服务器。

现在,您可以再次调用REST端点,并在Fake SMTP中查看结果!

但是,测试并不是指手动测试! 该应用程序仍然有用,但是我们要自动测试邮件代码。

单元测试邮件代码

为了能够自动测试邮件提交,我们将使用Wiser –一种基于SubEtha SMTP的单元测试邮件的框架/实用程序。 SubEthaSMTP的简单,低级API适用于编写几乎所有类型的邮件接收应用程序。

使用Wiser非常简单。 首先,我们需要向build.gradle添加一个测试依赖build.gradletestCompile("org.subethamail:subethasmtp:3.1.7") 。 其次,我们使用JUnit,Spring和Wiser创建一个集成测试:

@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服务器进行初始化,开始@Before方法和停止@Teardown方法。 发送消息后,将进行断言。 由于框架不提供任何断言,因此需要创建断言。 您将注意到,我们需要对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;}
}

摘要

仅需几行代码,我们就可以自动测试邮件代码。 本文介绍的示例并不复杂,但是它显示了使用SubEtha SMTP和Wiser入门很容易。

您如何测试您的邮件代码?

翻译自: https://www.javacodegeeks.com/2014/09/testing-mail-code-in-spring-boot-application.html

在Spring Boot应用程序中测试邮件代码相关推荐

  1. 如何在Spring Boot应用程序中使用配置文件

    你好朋友, 在本教程中,我们将学习如何在Spring Boot应用程序中使用配置文件. 我们将在本教程中讨论以下几点: 1.什么是Spring Boot Profile,为什么我们需要分析 2.如何使 ...

  2. 在使用Gradle构建的Spring Boot应用程序中覆盖Spring Framework版本

    如果要使用或仅通过Spring Boot检查Spring的最新版本,但当前的Spring Boot版本取决于旧的Spring版本,则需要稍微调整Gradle构建配置. 例如,在撰写本文时,Spring ...

  3. 谷歌 recaptcha_在Spring Boot应用程序中使用Google reCaptcha

    谷歌 recaptcha 介绍 Google的reCaptcha是一个库,用于防止漫游器将数据提交到您的公共表单或访问您的公共数据. 在本文中,我们将研究如何将reCaptcha与基于Spring B ...

  4. 将Spring Boot应用程序部署到Tomcat中

    "我喜欢编写身份验证和授权代码." 〜从来没有Java开发人员. 厌倦了一次又一次地建立相同的登录屏幕? 尝试使用Okta API进行托管身份验证,授权和多因素身份验证. 部署应用 ...

  5. cloud foundry_将Spring Boot应用程序绑定到Cloud Foundry中的服务的方法

    cloud foundry 如果要试用Cloud Foundry ,最简单的方法是下载出色的PCF开发人员或在Pivotal Web Services站点上创建试用帐户. 其余文章假定您已经安装了Cl ...

  6. 将Spring Boot应用程序绑定到Cloud Foundry中的服务的方法

    如果您想试用Cloud Foundry ,最简单的方法是下载出色的PCF开发人员或在Pivotal Web Services站点上创建试用帐户. 文章的其余部分假定您已经安装了Cloud Foundr ...

  7. Spring Boot微服务中Chaos Monkey的应用

    点击蓝色"程序猿DD"关注我哟 有多少人从未在生产环境中遇到系统崩溃或故障?当然,你们每个人迟早都会经历它.如果我们无法避免失败,那么解决方案似乎是将我们的系统维持在永久性故障状态 ...

  8. cognito_将Spring Boot应用程序与Amazon Cognito集成

    cognito 在本文中,我们将展示如何使用Spring Security 5.0中引入的OAuth 2.0客户端库 ,在Spring Boot应用程序中为身份验证用户使用Amazon Cognito ...

  9. 将Spring Boot应用程序与Amazon Cognito集成

    在本文中,我们将展示如何使用Spring Security 5.0中引入的OAuth 2.0客户端库 ,在Spring Boot应用程序中为身份验证用户使用Amazon Cognito服务. 什么是A ...

最新文章

  1. Python剑指offer:和为s的连续整数序列
  2. python锁有哪几种_python 可重入锁有什么用?
  3. Android4.1 新功能 新特性(转)
  4. 如何跨项目工作空间访问MaxCompute资源和函数?
  5. 安卓雷曼大冒险一直连接服务器,雷曼大冒险连接不到服务器是什么原因?网络连接失败的原因和解决办法[图]...
  6. ThinkPHP的介绍和安装
  7. laytpl语法_浅谈laytpl 模板空值显示null的解决方法及简单的js表达式
  8. GRE tunnel ×××
  9. 关于禁止ViewPager预加载问题【转】
  10. Origin科研绘图实战
  11. win7“您可能没有权限使用网络资源”的解决办法
  12. 计算机专业论文提纲,计算机硕士毕业论文提纲(范文精选)
  13. OpenCV实战之人脸美颜美型(六)——磨皮
  14. u盘插在电脑上没有反应_电脑无法识别U盘或插上U盘提示格式化
  15. This must be due to duplicate classes or playing wrongly with class loaders 1
  16. Google Map Event 谷歌地图事件
  17. html+css+js TAB切换
  18. 五分钟学会Python网络爬虫
  19. flex布局父项常见属性justify-content
  20. 【汇正财经顾晨浩】建筑行业,一带一路合作深化

热门文章

  1. json vs obj
  2. Spring-boot IDEA使用注解@ConfigurationProperties时报错解决
  3. Google浏览器截长图 不需要借助任何插件!!!
  4. cursor 过滤 android,Android cursor query方法详解
  5. MySQL事务管理+安全管理+MySQL数据类型
  6. Makefile浅尝
  7. throwable_您想了解的所有Throwable
  8. 抽取大小: 高斯sigma_无服务器:SLAppForge Sigma入门
  9. java迭代器删除两个_两个迭代器的故事
  10. intellij远程调试_IntelliJ中的远程调试Wildfly应用程序