Unit testing emails
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:
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
.
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:
- Have the test code poll a dedicated email box, matching emails with testcases and determining whether they are correct
- 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.
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