2008/04/13

Unit testing mail code

If you ever need to write unit tests for code that includes sending or receiving e-mails, check this Java library, called GreenMail. It's easy to use and free (Apache 2.0 License) !

It supports POP3, SMTP and IMAP (even with SSL!!!). You can browse its website to see some examples, but this is a little sample to show you how easy it is to use it:

...

public void testSmtpCode() throws Exception {

GreenMail greenMail = new GreenMail();
greenMail.start();

// ... Your code that sends e-mails

assertEquals("body", GreenMailUtil.getBody(greenMail.getReceivedMessages()[0]));
greenMail.stop();
}

public void testPop3Code() throws Exception {

GreenMail greenMail = new GreenMail();
greenMail.start();
MimeMessage message = ... // Build a javax.mail MIME Msg
User user = greenMail.setUser("to@localhost.com", "login-id", "password");
user.deliver(message);

// ...Your code that reads e-mails and processes them

// ... Your asserts with the processing

greenMail.stop();
}
...

The GreenMail server uses by default port numbers suitable for testing, not the usual ones in real sending/receiving, but you can change them if you want. The default port numbers are easy to rememeber, because they are the same as the standard ones prefixed by 3 (or 30 if the real port number has only 2 digits), so: the GreenMail SMTP server (standard port 25) uses a default port number 3025, the POP3 server (standard port 110) uses a default 3110, etc.

Happy testing !

No comments: