Use GreenMail For Spring Mail (JavaMailSender) JUnit 5 Integration Tests

Last Updated:  July 22, 2024 | Published: December 22, 2020

Sending emails is a common responsibility of enterprise applications. With the Spring Boot Starter Mail dependency, this becomes a trivial task. But how can we write integration tests to verify our functionality without sending actual emails to a user? With this blog post, we'll introduce GreenMail to write integration tests with JUnit 5 for sending emails with a Spring Boot application.

Spring Boot Project Setup

The project for demonstrating how to write integration tests for sending emails with the JavaMailSender is straightforward.

We're including the following Spring Boot Starters and are using Java 11:

Our application has one responsibility. Whenever we perform an HTTP POST to /notifications with valid payload, we'll notify a user by sending him/her an email:

We're using Bean Validation to ensure our clients pass a valid email address and non-empty email messages:

The actual email transport happens inside the NotificationService that uses the JavaMailSender from Spring that is auto-configured for us.

Sending Emails with the JavaMailSender from Spring

With Spring Boot's auto-configuration mechanism we get a ready-to-use JavaMailsender bean whenever we specify the spring.mail.* properties.

You can inspect the Spring Boot classes MailSenderAutoConfiguration and MailSenderPropertiesConfiguration if you want to understand how and when this auto-configuration happens.

A minimal configuration for using Google's Gmail SMTP server looks like the following:

We can then inject the JavaMailSender and start sending emails from our Spring Boot application:

For sending more advanced emails (e.g. with an attachment or HTML payload) we can create a MimeMessage using the JavaMailSender. However, for our testing demo the SimpleMailMessage is perfectly fine.

Now, when writing integration tests for this component of our application, we don't want to connect to a real SMTP server and deliver emails. Otherwise, our users would receive funny test messages whenever we run our test suite.

A better approach is to use a local sandbox email server to capture and verify all email traffic. GreenMail is such an email server that allows testing both sending and receiving mails. It's open-source, written in Java and we can easily integrate it into our project.

Writing Integration Tests with GreenMail and JUnit 5

There are multiple ways to integrate GreenMail for our integration test. Let's start with the most intuitive approach and register GreenMail's JUnit Jupiter extension.

We need the following GreenMail dependency for this:

While registering the GreenMail extension, we can configure the email server and decide which protocols we need for testing. As our demo application only sends emails, activating SMTP is enough:

As part of setting up the GreenMail server, we create a service user. We can use this information to override the configuration of our application by placing a application.yml inside src/test/resources with the following content:

The default behavior of this extension is to start and stop the GreenMail server for each test method. This will give us an empty email sandbox server for each test execution. This approach comes with a con of additional test execution time (almost negligible) as we're starting/stopping GreenMail before/after each test.

We can override this default behavior using .withPerMethodLifecycle(false) to share a GreenMail server for all test methods of a test class. When using this approach, however, we must ensure that our tests are independent and don't fail if a previous test sends an email to the same inbox. This can be mitigated by using random email addresses.

We use @SpringBootTest for our integration test to start the whole Spring Context. To invoke our endpoint we use the TestRestTemplate that is auto-configured for us as we also start the embedded Tomcat (webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT).

Putting it all together, a basic integration test for verifying the email transport looks like the following:

After invoking our endpoint we can request all captured emails from the GreenMail extension.

The test assertion above is quite naive as we expect the email to be delivered right after invoking our endpoint. We can also wrap our expectations with Awaitility to better verify this asynchronous operation of our application:

Using Testcontainers to Start the GreenMail Server

The GreenMail project also provides an official Docker image. In combination with Testcontainers, we can use this Docker image to start a local GreenMail Docker container for our integration tests.

We'll use the JUnit Jupiter extension from Testcontainers to manage the container lifecycle:

Next, we define a GenericContainer using the official GreenMail Docker image. We can use the environment variable GREENMAIL_OPTS to tweak the email server configuration and add our service user.

What's left is to tell Testcontainers which port to expose and which log message signals that the container is ready to receive traffic:

As Testcontainers will map GreenMail's 3025 port to a random and ephemeral port on our machine, the address is dynamic. Using @DynamicPropertySource we can override the dynamic parts of our email server configuration prior to starting the Spring TestContext.

Verifying the emails with this approach becomes a little bit more tricky. We could create a JavaMail Sesion after the test execution and connect to the dockerized GreenMail instance.

However, this setup might be useful if you want to share one GreenMail instance for multiple test classes and just need a running email server for your context to start. You can also use this standalone GreenMail Docker image during local development.

The source code for this demo on how to write integration tests for Spring's JavaMailSender with GreenMail and JUnit 5 is available on GitHub.

Have fun writing integration tests with GreenMail, Spring, and JUnit 5,

Philip

>