电子邮件发送集成测试

时间:2016-06-28 14:52:27

标签: java spring email integration-testing

请帮我写一封电子邮件发送的集成测试,即inreal发送电子邮件。

public interface MailSenderService {

void sendEmail(String to, String from, String subject, String body); }

邮件发件人类

@Service
public class MailSenderServiceImpl implements MailSenderService {
private static final Logger logger = LoggerFactory.getLogger(MailSenderServiceImpl.class);

@Autowired
private JavaMailSender javaMailSender;

@Autowired
Configuration freemarkerConfiguration;

private SimpleMailMessage composeMail(String to, String from, String subject, String body) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(from);
    message.setTo(to);
    message.setSubject(subject);
    message.setText(body);
    return message;
}

@Override
public void sendEmail(String to, String from, String subject, String body) {
    sendMessage(composeMail(to, from, subject, body));
}

@Async
private void sendMessage(SimpleMailMessage message) {
    Assert.notNull(javaMailSender, "Email Sender must not be null");
    javaMailSender.send(message);
}}

最后这是一个集成测试,但没有通过:

public class MailSenderServiceIT extends BaseServiceIntegrationTest {

@Autowired
private MailSenderService mailSenderService;

@Test
public void sendEmail() {
    mailSenderService.sendEmail("test1@gmail.com", "test2@gmail.com", "Test Subject",
            "Test Body");
    flushAndClear();
}

1 个答案:

答案 0 :(得分:0)

我们需要知道如何配置您的JavaMailSender。如果您想在集成测试中发送电子邮件,则需要配置JavaMailSender以使用本地配置。例如localhost:5555:

1) Then Field 2 is removed (id="ctl00_MainContent_cntrlDynamicField2")
2) As only 2 Fields are now displayed on the screen the ID's are now as follows
3) Field 1: (id="ctl00_MainContent_cntrlDynamicField1")
4) Field 3: (id="ctl00_MainContent_cntrlDynamicField2")

然后,您可以直接在测试中使用库subethasmtp创建服务器SMTP。我个人创建一个Junit规则来做到这一点:

JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost("localhost");
javaMailSender.setPort(5555);

因此,您可以在集成测试中执行类似的操作:

public class SMTPServerRule extends ExternalResource {

    private Wiser wiser;
    private String hostname;
    private int port;

    public SMTPServerRule() {
        this(25);
    }

    public SMTPServerRule(int port) {
        this("localhost", port);
    }

    public SMTPServerRule(String hostname, int port) {
        this.hostname = hostname;
        this.port = port;
    }


    @Override
    protected void before() throws Throwable {
        super.before();

        wiser = new Wiser(port);
        wiser.setHostname(hostname);
        wiser.start();
    }

    public List<WiserMessage> getMessages() {
        return wiser.getMessages();
    }

    @Override
    protected void after() {
        super.after();
        wiser.stop();
    }
}