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

Last Updated:  April 6, 2022 | 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

  • Hello Philip, thanks for this awesome tutorial! However, I have one problem:
    I’m pretty sure it is about withPerMethodLifecycle(false) method.
    I test 2 methods inside test class, when I test them separately everything works fine, however if I test the whole class – the MimeMessage[] array in second method holds 2 messages (one from previous method I suppose), not one. Setting methodLifecycle to true makes loading application context impossible(“mail server is not available”, “failed to load ApplicationContext”). Any ideas what might help? I’d be grateful!

    • Hi Igor,

      That’s the right observation. If you set withPerMethodLifecycle(false) it will use a single mail server and hence subsequent tests will see the data (speak emails) from previous tests. Can you share the entire stack trace and maybe a sample test over a GitHub issue?

      Kind regards,
      Philip

      • Thank you Philip for quick response! I posted a general question, as my code differs a little from the one at your tutorial. I’ll be grateful if you find some time to take a look at the issue #44
        Cheers

        • For future reference, the issue was test-connection: true inside the application.yml inside src/test/resources. This will try to reach to the sandbox email server before GreenMail had a chance to start it.

          Either remove this value entirely or set it to false.

  • {"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
    >