简体   繁体   English

当邮件包含模板时,如何在springboot中编写junit测试

[英]How to write junit test in springboot ,when mail contain template

how i can write junit for this mail code with template, here i am sending mail with template this is my Service class Method:我如何用模板为这个邮件代码写 junit,这里我用模板发送邮件这是我的服务 class 方法:

    @Service
    public class ServiceImpl {
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private Configuration configuration;
    @Value("${mail.send.to}")
    private String mailSendTo;
   
    public void sendMailOnEmailOptOut()
        throws MessagingException, IOException, TemplateException {
    String[] toAddressList = { mailSendTo };
    final String emailSubject = "email opt out testing";
    MimeMessage message = javaMailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, 
    MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
            StandardCharsets.UTF_8.name());
    helper.setTo(toAddressList);
    StringWriter stringWriter = new StringWriter();
    Map<String, Object> model = new HashMap<>();
    model.put("user", "this is just for testing");
    configuration.getTemplate("email.template.html").process(model, stringWriter);
    String emailContent = stringWriter.getBuffer().toString();
    helper.setText(emailContent, true);
    helper.setSubject(emailSubject);
    javaMailSender.send(message);
}

mail_send_to value come from property file and this is email.template.html is in src->main->resources template folder mail_send_to 值来自属性文件,这是 email.template.html 在 src->main->resources 模板文件夹中

  <!doctype html>
 <html lang="en">
  <head>
  <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, 
 maximum-scale=1.0, minimum-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>email opt-out testing</title>
 </head>
<body>
<div style="margin-top: 10px">Greetings, <b>${user} </b></div>
<div>welcome ! this is just for testing functionality of email </br></br></div>
</body>
</html>

You can use Java System Stubs to set environment variables for your unit tests, see this link https://www.baeldung.com/java-system-stubs您可以使用 Java System Stubs 为您的单元测试设置环境变量,请参阅此链接https://www.baeldung.com/java-system-stubs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM