Unit testing emails

By Confusion on Monday 23 June 2008 21:25 - Comments (9)
Categories: Software engineering, Testing, Views: 4.546

Sometimes the main purpose of an application is sending emails. But how do you unit test such a beast? Manually verifying the arrival and contents of the emails is fine for small amounts of email, but when the number of code paths and email varieties grows, you need an automated way to verify that the correct emails have been sent.

I have not yet done any research on existing libraries/frameworks that solve this problem, but I think it has to be either of two solutions:
  1. Have the test code poll a dedicated email box, matching emails with testcases and determining whether they are correct
  2. Launch a mock email server from your code, modify the test configuration in such a way that the mails are sent to that mail server and immediately check back whether the mails are correct.
The major drawback of the first solution is that you have no control over the moment when, and the order in which, the emails arrive. The largest problem of the second solution is writing/finding that server, that programmatically allows you to fetch the last received mail, etc.

If you already have an project layout and architecture that allows dependency injection and a seperate configuration for tests, then the second seems the obvious way to go: much more flexible and contained. Unfortunately, the project for which I would like to implement this does not have anything of the sort and adding that will not be easy, which make me prefer the first solution.

There is another thing to consider: library support. As I said, I have not yet searched, but my guess is that the second solution is the one for which there will be several solutions readily available, because it is the 'proper' solution. Moreover, I doubt whether I will find any existing solution that makes implementing the first solution easier.

I think I'll just go with the 'proper' solution :).