Unittesting e-mail sending using Spring
Published by peter August 29th, 2007 in e-mail, java, junit, smtp, spring, wiser.In previous projects I mostly skipped writing tests for sending mail. Mostly due to the fact that there is a dependency on a working SMTP server. This time I decided to invest some time in finding a solution for this problem.
It didn't have to look very far to find Wiser. Wiser is a very simple fake SMTP server designed for unit and system testing applications. You basically start it up, send mail to it and read the queue of messages it received.
Using it in unit test is indeed simple. First setup the server, and reconfigure mail senders in the Spring context:
-
@SuppressWarnings("unchecked")
-
@Override
-
protected void onSetUp() throws Exception {
-
super.onSetUp();
-
wiser = new Wiser();
-
wiser.setPort(2525);
-
wiser.start();
-
-
Map<String, JavaMailSenderImpl> ofType =
-
getApplicationContext().getBeansOfType(org.springframework.mail.javamail.JavaMailSenderImpl.class);
-
-
// reconfigure mailsenders in the spring context
-
for (Entry<String, JavaMailSenderImpl> bean : ofType.entrySet()) {
-
log.info(String.format("configuring mailsender %s to use local Wiser SMTP", bean.getKey()));
-
JavaMailSenderImpl mailSender = bean.getValue();
-
mailSender.setPort(2525);
-
mailSender.setHost("localhost");
-
}
-
}
Now you are ready to run a test:
-
public void testSendMailStrings() {
-
mailService.sendMail("test-sender@test.nl", "test-reciever@test.nl", "testing the mailservice", "testing the mail service, body");
-
-
assertEquals(1, wiser.getMessages().size());
-
WiserMessage m = wiser.getMessages().get(0);
-
assertEquals("test-sender@test.nl", m.getEnvelopeSender());
-
assertEquals("test-reciever@test.nl", m.getEnvelopeReceiver());
-
try {
-
MimeMessage message = m.getMimeMessage();
-
assertEquals("testing the mailservice", message.getSubject());
-
assertEquals("testing the mail service, body", (String)message.getContent());
-
} catch (MessagingException me) {
-
fail(String.format("MessagingException [%s] should not occur", me.getMessage()));
-
} catch (IOException ioe) {
-
fail(String.format("IOException [%s] should not occur", ioe.getMessage()));
-
}
-
}
And after this, make sure to stop the server so it can be started again for consequent tests:
-
@Override
-
protected void onTearDown() throws Exception {
-
wiser.stop();
-
}
Works like a dream!




















Indeed, SubethaSMTP is cool. I used it in my embedded e-mail server for Mule.
I knew I had seen it somewhere before!