Starting from version 5.7 Laravel suggests to use the array
driver for Mail during testing:
Unfortunately, the documentation tells nothing about this driver. According to the source code, the driver stores all the messages in memory without actually sending them. How to get the stored "sent" messages during unit testing (in order to check them)?
EDIT: With Laravel 9+, use:
$emails = app()->make('mailer')->getSymfonyTransport()->messages();
dd($emails);
Be sure your mail driver is set to array
in your .env
or phpunit.xml
file.
With Laravel 7+ or if you get error Target class [swift.transport] does not exist
use this to get the list of emails sent with the array driver:
$emails = app()->make('mailer')->getSwiftMailer()->getTransport()->messages();
$count = $emails->count();
$subject = $emails->first()->getSubject();
$to = $emails->first()->getTo();
$body = $emails->first()->getBody();
Call app()->make('swift.transport')->driver()->messages()
. The return value is a collection of Swift_Mime_SimpleMessage
objects.
An example of a full PHPUnit test:
public function testEmail()
{
Mail::to('[email protected]')->send(new MyMail);
$emails = app()->make('swift.transport')->driver()->messages();
$this->assertCount(1, $emails);
$this->assertEquals(['[email protected]'], array_keys($emails[0]->getTo()));
}
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