Skip to content

Commit

Permalink
Fix non-deterministic error in java email service test
Browse files Browse the repository at this point in the history
This commit fixes an issue where the JavaEmailServiceTest sometimes fails due to a jakarta.mail.MessagingException. The issue is encountered in the local dev environment. This is fixed by explicitly setting the from field in the MimeMessage. However, and in production, the from field should not be set as it is authenticated. The field can only be set in testing and via reflection.
  • Loading branch information
jgarivera committed Sep 5, 2024
1 parent 96896e3 commit c7f629f
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ class JavaEmailService implements EmailService {
private final JavaMailSender mailSender;
private final TemplateEngine templateEngine;

/**
* The default sender used in sending email. This is only used for testing and set via reflection.
* Having a null sender in GreenMail causes a non-deterministic failure relating to jakarta.mail.MessagingException.
*/
private String sender;

JavaEmailService(JavaMailSender mailSender, TemplateEngine templateEngine) {
this.mailSender = mailSender;
this.templateEngine = templateEngine;
Expand All @@ -30,6 +36,10 @@ public void send(String to, String subject, String template, Context context) th
MimeMessage mimeMessage = mailSender.createMimeMessage();
var helper = new MimeMessageHelper(mimeMessage, true);

if (sender != null) {
helper.setFrom(sender);
}

helper.setTo(to);
helper.setSubject(subject);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration;
import org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.util.ReflectionTestUtils;

import static org.assertj.core.api.Assertions.assertThat;

Expand All @@ -29,6 +30,8 @@ class JavaEmailServiceTest {

@Test
void it_sends_email() throws MessagingException {
ReflectionTestUtils.setField(emailService, "sender", null);

emailService.send("test@email.com", "Test subject", "email/welcome");

MimeMessage[] messages = greenMail.getReceivedMessages();
Expand Down

0 comments on commit c7f629f

Please sign in to comment.