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

The library has been released on GitHub and Maven Central.

Links : github.

The integration test comes from the github project : Source code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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());
}
}

Explanations

The example is quite straight forward.

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

1
2
@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

1
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!