gpt4 book ai didi

java - 如何测试JavaMailSender?

转载 作者:行者123 更新时间:2023-11-29 10:10:02 25 4
gpt4 key购买 nike

我没有什么问题。我创建了 MailService 来发送邮件。当我运行程序时,它起作用了。我在 resources/application.properties 中拥有的电子邮件的所有属性。我正在使用 spring-boot-starter-mail

@Service
public class MailService {
private JavaMailSender javaMailSender;

@Autowired
public MailService(JavaMailSender javaMailSender) {
this.javaMailSender = javaMailSender;
}

public void sendMail(String subject, String messageContent, String recipient)
throws MessagingException {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
messageHelper.setTo(recipient);
messageHelper.setSubject(subject);
messageHelper.setText(messageContent);
javaMailSender.send(mimeMessage);
}
}

但我不知道如何为它创建测试。我试过这样的事情,我使用 org.jvnet.mock-javamail:mock-javamail,但它不起作用:

public class MailServiceTest {
private MailService mailService;

@Mock
private JavaMailSender javaMailSender;


@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mailService = new MailService(javaMailSender);
Mailbox.clearAll();
}

@Test
public void sendMailTest() throws MessagingException, IOException {
String subject = "Some subject";
String body = "Some contents.";
String recipient = "test@test.com";

mailService.sendMail(subject, body, recipient);
List<Message> inbox = Mailbox.get(recipient);
assertTrue(inbox.size() == 1);
assertEquals(subject, inbox.get(0).getSubject());
assertEquals(body, inbox.get(0).getContent());
}
}

最佳答案

您可以测试 MimeMessage 是如何形成的:

public class EmailServiceTest {

private EmailServiceImpl emailServiceImpl;

private JavaMailSender javaMailSender;

private MimeMessage mimeMessage;

@Before
public void before() {
mimeMessage = new MimeMessage((Session)null);
javaMailSender = mock(JavaMailSender.class);
when(javaMailSender.createMimeMessage()).thenReturn(mimeMessage);
emailServiceImpl = new EmailService(javaMailSender);
}

@Test
public void emailTest() {
String recipient = "example@example.com"
EmailRequest request = new EmailRequest();
request.setRecipient(recipient);
emailServiceImpl.send(request);
assertEquals(recipient, mimeMessage.getRecipients(RecipientType.TO)[0].toString());
}
}

关于java - 如何测试JavaMailSender?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43387986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com