Swift Mailer is PHP library for sending emails. It’s a fantastic library, and highly recommended, but let’s talk testing.
External Code, Integration Tests
Whenever you use external code, you should have tests that use that code for real. Use mocks or other test doubles with external code makes assumptions about how that external library works. Those assumptions are probably wrong. The answer is a small set of integration tests where your code touches the outside library.
Swift Mailer, being a library, deserves some of that integration testing treatment. We don’t want to really send emails, but we do want to verify that our messages make it through the swift mailer system correctly.
Transports and Spools
Transports can do just about anything: send messages via a SMTP server or sendmail, write things to a file, or collect messages for later use. Collecting messages is called, in swift mailer terms, a spool. There’s already a transport that collects messages into a spool. If you’re familiar with Symfony, its swift mailer integration collects messages until the kernel terminate event fires then flushes them all with a real transport.
Swift Mailer Test Goals
Our goal here isn’t to really send emails. We just want to…
- Make sure we’re using swift mailer correctly.
- Ensure the expected email is sent through the system.
Using real objects takes care of the first item, and spools take care of the second. We’ll tell our objects to do stuff and collect messages along the way. Once the action is done, we can inspect our spool and the messages it contains.
Some Code, Finally
Swift has a built in memory spool, but it doesn’t give us access to the messages. So let’s extend it to make it countable and provide a getter for the messages.
Now we just need some set up code to create a mailer that uses our new spool. Here that as a PHPUnit test case.
Now we can use our mailer in objects that require it and verify that messages are sent after the fact. Here’s an example.
If you’re using the full stack Symfony framework, there’s a built in way to check emails in acceptance (functional) tests. This method is meant to help with a bit lower level of testing and doesn’t rely on the full stack framework’s test system.