Writing an integration test with a mail server

This is a simple example of to demonstrate how to use the library fakesmtp-junit-runner to write integration tests with mail servers.

The library has been released on and Maven Central.



public class FakeSmtpIntegrationTest {

@Rule
public FakeSmtpRule smtpServer = new FakeSmtpRule(ServerConfiguration.create().port(2525).charset("UTF-"));

private MailSender mailSender = new MailSender("localhost", 2525);

/**
* Tests that no  has been received at the startup.
*/
@Test
public void testNoMailReceived() {
Assert.assertTrue(smtpServer.mailBox().isEmpty());
}

/**
* Tests that the relay domains are not defined, by default.
*/
@Test
public void testRelayDomainsAreNotConfigured() {
Assert.assertTrue(smtpServer.relayDomains().isEmpty());
}

/**
* Sends a  and controls that it has been treated.
*
* @throws MessagingException
*/
@Test
public void testMailSending_withoutRelay() throws MessagingException {
// GIVEN A  SERVER WITHOUT RELAY DOMAIN
// THEN I SEND A 
mailSender.sendMail("sender@example.org", "receiver@example.org");

// I DONT HAVE MAILS IN MY MAILBOX
Assert.assertTrue(smtpServer.mailBox().isEmpty());
// AND A  HAS BEEN REJECTED
Assert.assertEquals(1, smtpServer.rejectedMails().size());
}

/**
* Sends a  and controls that it has been treated.
*
* @throws MessagingException
*/
@Test
public void testMailSending_withRelay() throws MessagingException {
// GIVEN A  SERVER WITH RELAY DOMAIN
smtpServer.getServerConfiguration().relayDomains("example.org");
// THEN I SEND A 
mailSender.sendMail("sender@example.org", "receiver@example.org");

// I HAVE ONE  IN MY MAILBOX
Assert.assertEquals(1, smtpServer.mailBox(). size());
// AND NO  HAS BEEN REJECTED
Assert.assertEquals(0, smtpServer.rejectedMails().size());
}

}

Links : github.

The integration test comes from the github project : Source code

 

 Explanations

The example is quite straight forward.

First step: you have to declare the JUnit @Rule provided by the library.

 
@Rule
public FakeSmtpRule smtpServer = new FakeSmtpRule(ServerConfiguration.create().port(2525).charset("UTF-8"));

Don’t forget to provide the appropriate server configuration to receive your mails 🙂 You can check Javadoc there

Second step: Injects with Spring or declares the component you have wrote to send mails

 
private MailSender mailSender = new MailSender("localhost", 2525);

Third step: Write your testcases.

Don’t forget to declare in your test cases the relay domains that will be allowed to receive my your smtp servers. Mails that don’t match the relay domains are automatically rejected.

Next to read  CompletableFuture and Java 8 Reactive

Have fun!