测试邮件是否使用Java成功发送

时间:2019-06-13 10:11:03

标签: java spring unit-testing testing greenmail

我有一个mailingService发送邮件:

@Component
public class MailingServiceImpl implements MailingService{

    @Autowired
    JavaMailSenderImpl mailSender;

    @Override
    public void sendMail(String sender, String receiver, String subject, String content) {

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(sender);
        message.setTo(receiver);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
    }
}

,我正在为此void sendMail(...)编写测试,我需要检查邮件是否已成功发送。我发现GreenMail是我当前正在尝试用于测试的代码,如下所示:

public class MailingServiceImplTest {

    private MailingServiceImpl mailingServiceImpl;

    @Autowired
    private JavaMailSenderImpl mailSender;

    @PostConstruct
    public void testConnection() {
        try {
            mailSender.testConnection();
        } catch(MessagingException ex) {
            throw new IllegalStateException("[Warning] Mail server is not available. " + ex);
        }
    }

    @Rule
    public final GreenMailRule greenMail = new GreenMailRule(ServerSetupTest.SMTP);

    @Test
    public void testSendMail() throws IOException {
        GreenMailUtil.sendTextEmailTest(receiver, sender, subject, content);
        // GreenMailUtil.sendTextEmailTest(to, from, subject, body);  -- here I could use the GreenMailUtil sendTextEmailTest, but I need to use my void sendMail function
        MimeMessage[] emails = greenMail.getReceivedMessages();
//      assertEquals(1, emails.length);
    }

任何想法如何测试我的方法? GreenMail(例如example“使用JUint(基于规则的设置)”部分)不是我尝试过的唯一工具,尝试过Dumbster(例如下面的example,但是{{ 1}}需要使用字符串作为参数,我无法传递方法。我做错了什么吗?帮助

编辑

我的JavaMailSenderImpl设置:

sendMessage

最近在调试中发现 @Bean public JavaMailSenderImpl mailSenderService(MailingServiceImpl mailingServiceImplementation, @Value("${mail.host}") String host, @Value("${mail.port}") int port, @Value("${mail.username}") String username, @Value("${mail.password}") String password) { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost(host); mailSender.setPort(port); mailSender.setUsername(username); mailSender.setPassword(password); return mailSender; } @Autowired MailingServiceImpl ..但是为什么呢?我不太了解。

1 个答案:

答案 0 :(得分:0)

Greenmail等正在启动可以从您的应用程序访问的本地MailService。我还没有使用它,所以不要按原样使用代码,但是从我的角度来看,您的测试应该看起来很不错。像这样:

@Autowired
private MailingServiceImpl mailingServiceImpl;

@Rule
public final GreenMailRule greenMail = new GreenMailRule(ServerSetupTest.SMTP);

@Test
public void testSendMail() throws IOException {
    mailingServiceImpl.sendMail("sender", "receiver", "subject", "content");
    MimeMessage[] emails = greenMail.getReceivedMessages();
    assertEquals(1, emails.length);
}

当然,必须正确配置JavaMailSender才能使用本地GreenMail-SMTP服务,并且当然,弹簧测试设置必须正确(假设您要使用spring)。

使用spring boot时,这样的配置就足够了:

spring.mail.host=localhost
spring.mail.port=3025 #Default port of greenmail?!