Bookmark this on Hatena Bookmark
Share on LinkedIn
Pocket

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.
*/
@
public void testNoMailReceived() {
Assert.assertTrue(smtpServer.mailBox().isEmpty());
}

/**
* Tests that the relay domains are not defined, by default.
*/
@
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 : 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 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!

Share on LinkedIn
Pocket


Sylvain Leroy

Senior Software Quality Manager and Solution Architect in Switzerland, I have previously created my own company, Tocea, in Software Quality Assurance. Now I am offering my knowledges and services in a small IT Consulting company : Byoskill and a website www.byoskill.com Currently living in Lausanne (CH)