Mailing box

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

The library has been released on GitHub and Maven Central.



public class FakeSmtpIntegrationTest {

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

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

/**
* Tests that no mail 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 mail and controls that it has been treated.
*
* @throws MessagingException
*/
@Test
public void testMailSending_withoutRelay() throws MessagingException {
// GIVEN A MAIL SERVER WITHOUT RELAY DOMAIN
// THEN I SEND A MAIL
mailSender.sendMail("sender@example.org", "receiver@example.org");

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

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

// I HAVE ONE MAIL IN MY MAILBOX
Assert.assertEquals(1, smtpServer.mailBox(). size());
// AND NO MAIL 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.

Have fun!

By sleroy

Leave a Reply

Your email address will not be published. Required fields are marked *