|
| 1 | += Mock JavaMail |
| 2 | + |
| 3 | +== What is this? |
| 4 | + |
| 5 | +Testing JavaMail applications is more difficult than necessary, because it involves a lot of setup outside the test program. |
| 6 | +Doing this correctly in a portable way so that anyone in your team can run the test is almost impossible. |
| 7 | + |
| 8 | +Mock JavaMail comes to the rescue. This project takes advantage of pluggability in JavaMail, so that you can send/receive e-mails against a temporary in-memory "mailbox". |
| 9 | +For example, when this JAR is in your classpath, the following code that normally sends e-mail to me actually just sends the e-mail to an in-memory mailbox: |
| 10 | + |
| 11 | +[source,java] |
| 12 | +---- |
| 13 | +MimeMessage msg = new MimeMessage(); |
| 14 | +... |
| 15 | +msg.setRecipients(TO,"[email protected]"); |
| 16 | +Transport.send(msg); |
| 17 | +---- |
| 18 | + |
| 19 | +You can access this e-mail programatically like this: |
| 20 | + |
| 21 | +[source,java] |
| 22 | +---- |
| 23 | +List<Message> inbox = Mailbox.get("[email protected]"); |
| 24 | +assertEquals(inbox.size(),1); // was the e-mail really sent? |
| 25 | +---- |
| 26 | + |
| 27 | +You can also directly add messages to this list to emulate e-mails in the inbox, instead of using the JavaMail API. |
| 28 | +Staging e-mails like this is useful for testing the server. |
| 29 | + |
| 30 | +Similarly you can access these e-mails programatically by using JavaMail, just like you normally do: |
| 31 | + |
| 32 | +[source,java] |
| 33 | +---- |
| 34 | +Session session = ...; |
| 35 | +Store store = session.getStore("pop3"); // imap would do, too |
| 36 | +
|
| 37 | +// connect to [email protected] mailbox |
| 38 | +store.connect("example.com","first.last","anything"); |
| 39 | +
|
| 40 | +Folder folder = store.getFolder("INBOX"); |
| 41 | +folder.open(Folder.READ_WRITE); |
| 42 | +Message[] msgs = folder.getMessages(); |
| 43 | +---- |
| 44 | + |
| 45 | +This allows you to test both the sending side and receiving side. |
| 46 | +All you need to do is to drop the JAR in the classpath during the test. |
| 47 | + |
| 48 | +== Testing error handling behaviors |
| 49 | + |
| 50 | +`Mailbox` can be marked as 'error' programatically, which causes all sending/receiving operations to fail. |
| 51 | +This can be used to test the error handling behavior of the application. |
| 52 | + |
| 53 | +[source,java] |
| 54 | +---- |
| 55 | +Mailbox inbox = Mailbox.get("[email protected]"); |
| 56 | +inbox.setError(true); |
| 57 | +---- |
| 58 | + |
| 59 | +== Related projects |
| 60 | + |
| 61 | +If this project isn't what you were looking for, see the following related projects: |
| 62 | + |
| 63 | +* http://subethasmtp.tigris.org/wiser.html[Wiser] |
| 64 | +* http://quintanasoft.com/dumbster/[dumbster] |
| 65 | +* https://aspirin.dev.java.net/[Aspirin] |
0 commit comments