I want to unit test a Java application that fetches mails from an email inbox, much like this guy. Currently, I run the unit tests against a real mailbox on our company's real mailserver which was easy to set up, but has the following disadvantages:
I would like to fire up an IMAP server on a local port, which fakes an inbox based on test data stored in files alongside the test classes. I can think of the following approaches:
I would like to avoid the first option, it sort of looks straightforward, but I'm guessing from similar experience that there's a long tail of work waiting further down the road. Just think of wanting to test secure connections etc. Similarly, the second option seems like to much work, but I haven't found a mail server yet that would allow for the third one.
If it matters, I'm using Maven and TestNG during the build process.
While doing unit testing using junit you will come across places where you want to mock classes. Mocking is done when you invoke methods of a class that has external communication like database calls or rest calls.
We can use Mockito class mock() method to create a mock object of a given class or interface. This is the simplest way to mock an object. We are using JUnit 5 to write test cases in conjunction with Mockito to mock objects.
Greenmail might be useful.
GreenMail is an open source, intuitive and easy-to-use test suite of email servers for testing purposes. Supports SMTP, POP3, IMAP with SSL socket support.
Write a test which relies on an existing mail server to check that your code can access it. This code should do the proper setup (i.e. it should send itself a mail). Guard this test with some global variable or System.property
so you can enable/disable it at runtime.
Move the code to access the server into an isolated class.
Override this class in your tests. In the test, just check that the mail text is correct. If you get a bug report that accessing the server is broken, enable the "access the real server test" and check.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With