Today is Wednesday, 19th July 2017

Archive for the ‘JavaMail’ Category

Unit Testing Java Email Code with Fake SMTP Server

What is your testing strategy for sending emails from your Java application? Do you hard-code your developer email in the application? I’ve been there and done that (not too proud though). Ideally, you would like to use the actual email addresses in your testing process. However, you do not want to send the email to the actual recipient. You would also like to view the message and validate/assert the message is correct.

One possible solution is to install a local email server and run your tests against the server. However, this requires that you create accounts for all of your test data or customer data.

I found a really great open-source solution to this problem, Wiser. Wiser is a fake SMTP server written in Java. You can use it for unit testing your application that sends email. It accepts all email messages and stores them in memory. Then you can call an API method to retrieve the messages. All of this can run in the same VM as your unit test…really slick!

It is really easy to get started using Wiser:

Step 1:  Start Wiser in your Java code

Wiser wiser = new Wiser();
wiser.setPort(2500); // Default is 25
wiser.start();

Step 2:  Call your Java code to send email to the Wiser server

// your JavaMail code

Step 3: Retrieve messages from Wiser

for (WiserMessage message : wiser.getMessages()) {
String envelopeSender = message.getEnvelopeSender();
String envelopeReceiver = message.getEnvelopeReceiver();
MimeMessage mess = message.getMimeMessage();
// now do assert the message headers and contents
}

That’s it.  Take a look at Wiser’s website to get the JAR files. Enjoy!

Share