Mocking JavaMail

Dec 8, 2011   #java  #mail  #test 

I had to test the mail sending capabilities of my code without having a mail server at hand. I came across Mock-JavaMail.

It mocks the whole JavaMail API so that all mail messages are not sent to a SMTP server but to in-memory mailboxes.

To include it in your tests, you just have to add this dependency in your pom.xml if you are using Maven:


(Make sure to add the test scope or otherwise your production configuration will not send real emails.)

After sending mail from your application code in your test cases, you can easily access the mailboxes and check the messages and their content like this:

List<Message> inbox = org.jvnet.mock_javamail.Mailbox.get("");


Message message = inbox.get(0);
assertEquals("Expected Subject", message.getSubject());