TDD of mail services
Lately I’ve come to the conclusion that TDD is the only viable way to develop software; I don’t mean to say that you must use TDD to write even your PHP homepage, but if your team is developing a project for a customer, and you want this project to be mantainable and cause less headaches than possible, TDD is one of the must-have practices. Anyway, that’s a big topic and I might post more details about it in the future.
One of the nice things you face when you embrace TDD is that there’re some parts (or some APIs) which are difficult to unit test. And the nice thing is that you can (quite) always find cool tools or nice tricks to do that. Let’s take JavaMail, for example.
JavaMail is an API which is tricky to test. How can you test a simple method like this?
public void sendJobSubmissionNotification(User user)
{
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", configuration.getSmtpServer());
props.setProperty("mail.smtp.port", configuration.getSmtpServerPort());
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(configuration.getReplyToMailAddressForNotifications()));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(user.getEmail(), false));
msg.setSubject(configuration.getSubjectOfNewJobSubmissionNotificationMail());
msg.setText(configuration.getBodyOfNewJobSubmissionNotificationMail());
msg.setSentDate(new Date());
Transport.send(msg);
}
|
The answer of Dumbster is “use a fake SMTP server!” |
|
The Dumbster is a very simple fake SMTP server designed for unit and system testing applications that send email messages. It responds to all standard SMTP commands but does not deliver messages to the user. The messages are stored within the Dumbster for later extraction and verification.
Dumbster is a configurable, fake SMTP server you can use for your test. Not only it intercepts all the emails you send, but makes it possible to analyze them in order to check their correctness. Let’s write a test for our method:
public void testJobSubmissionNotification()
{
SimpleSmtpServer smtpServer = SimpleSmtpServer.start(10025);
myMailService.sendJobSubmissionNotification(new User("manager","manager@manager.mm"));
smtpServer.stop();
assertEquals(1,smtpServer.getReceivedEmailSize());
SmtpMessage email = (SmtpMessage) smtpServer.getReceivedEmail().next();
assertEquals("manager@manager.mm", email.getHeaderValue("To"));
assertEquals("noreplay@dummy.du", email.getHeaderValue("From"));
assertEquals("My message subject", email.getHeaderValue("Subject"));
assertEquals("My message body", email.getBody());
}
Isn’t is cool?

4 Comments