How to get messages sent with the `array` mail driver?

Viewed 2824

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)?

3 Answers

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('user@example.com')->send(new MyMail);

    $emails = app()->make('swift.transport')->driver()->messages();
    $this->assertCount(1, $emails);
    $this->assertEquals(['user@example.com'], array_keys($emails[0]->getTo()));
}

My custom assertion based on Finesse's answer.

protected function assertMailSentTo($user, $expected = 1)
{
    $messages = app('swift.transport')->messages();

    $filtered = $messages->filter(function ($message) use ($user) {
        return array_key_exists($user->email, $message->getTo());
    });

    $actual = $filtered->count();

    $this->assertTrue(
        $expected === $actual,
        "Sent {$actual} messages instead of {$expected}."
    );
}
Related