Spring Mail Integration Testing with JUnit and GreenMail Example

摘要: In this example we show how to use Spring Mail and write Integration Tests using JUnit and GreenMail. We start by writing a simple email service that sends out emails. We want to verify that this email service sends out correct emails, so we use GreenMail – which is an open source test suite of email servers for testing purposes.

In this example we show how to use Spring Mail and write Integration Tests using JUnit and GreenMail. We start by writing a simple email service that sends out emails. We want to verify that this email service sends out correct emails, so we use GreenMail – which is an open source test suite of email servers for testing purposes.

Project Structure

Let’s start by looking at our project structure.

Maven Dependencies

We use Apache Maven to manage our project dependencies. Make sure the following dependencies reside on your class-path.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

    <name>Spring MAIL - ${project.artifactId}</name>



        <!-- testing -->



Mail Object

We are using this Mail object to pass as an argument for our EmailService to encapsulate the details of an email message and content.

package com.memorynotfound.mail;

public class Mail {

    private String from;
    private String to;
    private String subject;
    private String content;

    public Mail() {

    public Mail(String from, String to, String subject, String content) {
        this.from = from;
        this.to = to;
        this.subject = subject;
        this.content = content;

    public String getFrom() {
        return from;

    public void setFrom(String from) {
        this.from = from;

    public String getTo() {
        return to;

    public void setTo(String to) {
        this.to = to;

    public String getSubject() {
        return subject;

    public void setSubject(String subject) {
        this.subject = subject;

    public String getContent() {
        return content;

    public void setContent(String content) {
        this.content = content;

    public String toString() {
        return "Mail{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", subject='" + subject + '\'' +
                ", content='" + content + '\'' +

Sending Email Service

We use this service to demonstrate how to send a simple email, which we can verify in our integration tests.

package com.memorynotfound.mail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

public class EmailService {

    private JavaMailSender emailSender;

    public void sendSimpleMessage(Mail mail){
        SimpleMailMessage message = new SimpleMailMessage();



Bootstrap Application

We use spring boot to bootstrap our application.

package com.memorynotfound.mail;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);


Test Email Configuration Properties

We configure integration tests using the application-test.yml file which is located in the src/test/resources folder.

# application.yml

    default-encoding: UTF-8
    host: localhost
    username: username
    password: secret
    port: 2525
        debug: false
          debug: false
          auth: true
          starttls: true
    protocol: smtp
    test-connection: false

Create SmtpServerRule

We create a custom JUnit Rule called SmtpServerRule by extending from the ExternalResource class. In this class we start and stop a GreenMail server before and after each Integration Test. This allows us to intercept incoming emails.

package com.memorynotfound.mail.test;

import com.icegreen.greenmail.util.GreenMail;
import com.icegreen.greenmail.util.ServerSetup;
import org.junit.rules.ExternalResource;
import javax.mail.internet.MimeMessage;

public class SmtpServerRule extends ExternalResource {

    private GreenMail smtpServer;
    private int port;

    public SmtpServerRule(int port) {
        this.port = port;

    protected void before() throws Throwable {
        smtpServer = new GreenMail(new ServerSetup(port, null, "smtp"));

    public MimeMessage[] getMessages() {
        return smtpServer.getReceivedMessages();

    protected void after() {

Spring Mail Integration Testing with JUnit and GreenMail Example

Finally, we can start writing our Integration Test.

  • @SpringBootTest – specifies that the unit tests is a spring boot based test and configures appropriately.
  • @ActiveProfiles("test") – specifies that the profile test is used to run the tests.
  • @RunWith(SpringRunner.class) – specifies that JUnit will run the tests with the SpringRunner class.

We configure the SmtpServerRule with the JUnit @Rule annotation. This marks the custom rule to be invoked before and after each integration test. And allows us to intercept incoming emails. Finally, we make some assertions and validate if the sent emails are equal to the received emails.

package com.memorynotfound.mail.test;

import com.memorynotfound.mail.EmailService;
import com.memorynotfound.mail.Mail;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class SpringMailIntegrationTest {

    private EmailService emailService;

    public SmtpServerRule smtpServerRule = new SmtpServerRule(2525);

    public void shouldSendSingleMail() throws MessagingException, IOException {
        Mail mail = new Mail();
        mail.setFrom("[email protected]");
        mail.setTo("[email protected]");
        mail.setSubject("Spring Mail Integration Testing with JUnit and GreenMail Example");
        mail.setContent("We show how to write Integration Tests using Spring and GreenMail.");


        MimeMessage[] receivedMessages = smtpServerRule.getMessages();
        assertEquals(1, receivedMessages.length);

        MimeMessage current = receivedMessages[0];

        assertEquals(mail.getSubject(), current.getSubject());
        assertEquals(mail.getTo(), current.getAllRecipients()[0].toString());



JUnit GreenMail Integration Test Results

If your configuration is correct, you should receive the following email in your inbox.


上一篇: Spring Security + Spring LDAP Authentication Configuration Example
下一篇: Spring Mail Sending Email with Thymeleaf HTML Template Example
 评论 ( What Do You Think )


  • 微信公众号

  • 我的微信


1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号