首页 > 解决方案 > 电子邮件服务的 Junit 测试

问题描述

我想测试一个使用 smtp.gmail.com 发送电子邮件的简单方法。发送电子邮件的人和密码在 application.properties 中设置,并且正在使用 @Value 注释。我如何为这种方法编写 Junit 测试?

我曾尝试使用假 smtp 和绿色邮件。但我不明白它是如何工作的以及如何实施。我正在使用gradle。我在 build.gradle 中包含了虚假的 smtp,但不知道如何更改电子邮件的发送位置。

这是我的 Junit 测试类:

 import static org.junit.Assert.*;

 import javax.mail.MessagingException;
 import javax.mail.internet.AddressException;

 import org.junit.Test;

 import com.Email.EmailServiceApplication;

 public class EmailServiceTest {

    @Test
    public void test() throws AddressException, MessagingException {

        EmailServiceApplication esa = new EmailServiceApplication();
        assertEquals(esa.sendEmail("abhi", 1), "Email sent successfully");
    }

}

这是我的方法:

private void sendmail(EmailMessage emailmessage, int ver) throws AddressException, MessagingException {
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.ssl.trust", "smtp.gmail.com");     
    props.put("mail.smtp.starttls.enable", "true");     
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    // get session for email
    Session session = Session.getInstance(props, 
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }           
    });

    if(ver == 1) {
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(username, false));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailmessage.getTo_address()));
        msg.setSubject("Job uploaded");
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText("job has been uploaded successfully!");        
        Multipart multipart = new MimeMultipart();
        // Set text message part
        multipart.addBodyPart(messageBodyPart);
        // Send the complete message parts
        msg.setContent(multipart);
        msg.setSentDate(new Date());
        // Send
        Transport.send(msg);
    }
}

标签: javaspring-bootemailjunitjakarta-mail

解决方案


在当前状态下,您的代码很难测试,因为电子邮件提供商的设置和 sendlogic 使用相同的方法。这使得无法将电子邮件发送到 smtp.gmail.com 以外的其他位置。

我建议将这两个方面分成一些较小的方法。这使得传入例如greenmail 邮件提供商成为可能。

就像是:

Session createMailSession() {
    ... your original session creation logic here
    return session;
}

void doSendMail(Session session, EmailMessage emailMessage, int ver) {
    if(ver == 1) {
        ... your original sending logic here
    }
}

public void sendMail(EmailMessage emailmessage, int ver) {
  doSendMail(getSession(), emailMessage, ver);
}

现在您可以使用不同的电子邮件提供商测试发送逻辑,例如 greenmail:

@Test
public void canSendMail() {
   Session testSession = greenMail.getSmtp().createSession()
   doSendMail(testSession, ..., ...)
   assertEquals(1, greenMail.getReceivedMessages().length)
}

推荐阅读