要如何對JavaMail-API做單元測試呢? 在Stack Overflow上不少人推薦 GreenMail,GreenMail支援SMTP, POP3, IMAP,可以對sender和receiver進行測試,就來試用看看。
Sender1
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
43public class MailSenderTest {
private GreenMail greenMail;
private MimeMessage message;
public void setUp() throws Exception {
greenMail = new GreenMail(ServerSetupTest.SMTP);
greenMail.start();
Properties properties = System.getProperties();
properties.put("mail.smtp.host", "localhost");
properties.put("mail.smtp.port", ServerSetupTest.SMTP.getPort());
Session session = Session.getInstance(properties);
message = new MimeMessage(session);
message.setFrom(new InternetAddress("test@test.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("test1@test.com", false));
message.setSubject("subject");
message.setText("text");
message.setSentDate(new Date());
}
public void tearDown() throws Exception {
greenMail.stop();
}
public void testSend() throws Exception {
// [Start] Replace this with your send code
// Sender.send(message);
// [End]
MimeMessage[] messages = greenMail.getReceivedMessages();
Assert.assertNotNull(messages);
Assert.assertEquals(1, messages.length);
MimeMessage m = messages[0];
Assert.assertEquals("subject", m.getSubject());
Assert.assertTrue(String.valueOf(m.getContent()).contains("text"));
Assert.assertEquals("test@test.com", m.getFrom()[0].toString());
}
}
Receiver1
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
34public class MailReceiverTest {
private GreenMail greenMail;
private String subject;
private String body;
public void setUp() throws Exception {
greenMail = new GreenMail(ServerSetupTest.SMTP);
greenMail.start();
subject = GreenMailUtil.random();
body = GreenMailUtil.random();
GreenMailUtil.sendTextEmailTest("test@localhost.com", "test1@localhost.com", subject, body);
}
public void tearDown() throws Exception {
greenMail.stop();
}
public void testReceiver() throws Exception {
// [Start] Replace this with your receive code
// Message message = Receiver.receive();
// [End]
Assert.assertNotNull(message);
Assert.assertEquals(message.getTo(), "test@localhost.com");
Assert.assertEquals(message.getFrom(), "test1@localhost.com");
Assert.assertEquals(message.getSubject(), subject);
Assert.assertEquals(message.getBody(), body);
}
}
使用GreenMail進行測試,嚴格來說並不屬於unit test,某種程度來說它也是屬於mail server,否則就必須mock Transport和Session。是否能透過mock Transport和Session來達到測試效果,這跟你的mail class設計有關。以實用性、方便性和功能性,GreenMail算是一個不錯測試mail的framework。