Digital Sanctum

Personal blog of Shane Witbeck Tags · Archive · About

How to Test Java Mail Without a Server

Published: 21 Apr 2011

If you have an app that sends email and you want to test it without a mail server, I recently found an elegant solution. The solution involves using the Spring framework and an open source library called subethasmtp, a server-side SMTP library for Java.

First, here’s what a typical Spring context might look like to send an email out using Spring’s SimpleMailMessage.

Second, here’s the test where I’m leveraging one of Spring’s Abstract test classes (AbstractJUnit4SpringContextTests) and subclassing it to allow me to easily dependency inject what I need to test.

Looking at the setup for the test denoted by JUnit’s @Before annotation, I’m using subethasmtp’s Wiser framework to start a mock mail server (not an actual mail server).

Here’s a util class where we call a method which finds all the Spring-managed classes which are JavaMailSenderImpl and reconfigures them to use the same host and port that we set in the test setup above. In this case the host is set to “localhost” and the port is set to 2500.

So with this setup you have a portable test that can be run anywhere including on a Continuous Integration server without worrying about setting up an email server.

Tags: #subethasmtp#java#junit#email#testing#spring