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:
<dependency> <groupId>org.jvnet.mock-javamail</groupId> <artifactId>mock-javamail</artifactId> <version>1.9</version> <scope>test</scope> </dependency>
(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("email@example.com"); assertFalse(inbox.isEmpty()); Message message = inbox.get(0); assertEquals("Expected Subject", message.getSubject()); ...