Reputation: 11
how i can write junit for this mail code with template , here i am sending mail with template this is my Service class Method:
@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
<!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>
Upvotes: 0
Views: 847
Reputation: 209
You can use Java System Stubs to set environment variables for your unit tests, see this link https://www.baeldung.com/java-system-stubs
Upvotes: 1