javatestingsmtpjunit5apache-james

How to create mock email service in Java?


I am writing a small testing library with different mock services such as HTTP, SFTP, Buckets, Email.

I have a mind block when it comes to Email Mock service. I find a Apace James docs and an article but I don't see how I can adapt it to my interface and it is confusing to work with SMTP Servers.

interface TestServer {

    void start();

    void stop();

}

The idea is to create an implementation, so the whole setup will be in the constructor and I need to start and stop Mock only in set up and tear down phases.

How can I do it with the Apache James service?

I use Java 11, Spring Boot, and JUnit 5.


Solution

  • You can achieve this by using org.apache.james.smtpserver.netty.SMTPServer. To do this you will need some dependencies.

    For Gradle :

    implementation group: 'org.apache.james', name: 'james-server-protocols-smtp', version: '3.5.0'
    implementation group: 'org.apache.james', name: 'metrics-api', version: '3.5.0'
    implementation group: 'org.apache.james', name: 'metrics-logger', version: '3.5.0'
    implementation group: 'org.apache.james.protocols', name: 'protocols-netty', version: '3.5.0'
    

    For Maven:

        <dependency>
            <groupId>org.apache.james</groupId>
            <artifactId>james-server-protocols-smtp</artifactId>
            <version>3.5.0</version>
        </dependency>
    
        <dependency>
            <groupId>org.apache.james.protocols</groupId>
            <artifactId>protocols-netty</artifactId>
            <version>3.5.0</version>
        </dependency>
    
        <dependency>
            <groupId>org.apache.james</groupId>
            <artifactId>metrics-api</artifactId>
            <version>3.5.0</version>
        </dependency>
    
        <dependency>
            <groupId>org.apache.james</groupId>
            <artifactId>metrics-logger</artifactId>
            <version>3.5.0</version>
        </dependency>
    

    SMTPServer is part of james-server-protocols-smtp but others are needed for metrics.

    A sample implementation of your interface can look like this :

    public class MySmtpServer implements TestServer {
    
        private final SMTPServer smtpServer;
    
        public MySmtpServer(final int port) {
            MetricFactory metricFactory = new DefaultMetricFactory();
            SmtpMetrics smtpMetrics = new SmtpMetricsImpl(metricFactory);
            SMTPServer smtpServer = new SMTPServer(smtpMetrics);
            smtpServer.setListenAddresses(new InetSocketAddress(port));
            this.smtpServer = smtpServer;
        }
    
        @Override
        public void start() {
            smtpServer.start();
        }
    
        @Override
        public void stop() {
            smtpServer.stop();
        }
    }