How to Write a unit test with laravel queue mail? How to Write a unit test with laravel queue mail? laravel laravel

How to Write a unit test with laravel queue mail?


You would do something like this (depending on your setup):

<?phpnamespace Tests\Feature;use App\User;use App\Mail\Welcome;use Illuminate\Support\Facades\Mail;class SendInvitationEmailTest extends TestCase{    /** @test */    function mails_get_queued()    {        Mail::fake();        $user = factory(User::class)->create();        $this->post('/route/to/send/the/welcome/mail');        Mail::assertQueued(Welcome::class, 1);        Mail::assertQueued(Welcome::class, function ($mail) use ($user) {            return $mail->user->id === $user->id;        });    }}


I would recommend grabbing the queued emails from Mail::queued. It's a simple array that then gives you all the power you want.

Like this:

$queuedEmails = Mail::queued(CustomerEmail::class);$this->assertCount(1, $queuedEmails);$email = $queuedEmails[0];$this->assertEquals('status_complete', $email->handle);

You can run asserts as you're used to, which provide more meaningful messages in the case of failure. Unfortunately, Mail::assertQueued's failure report isn't very specific or helpful:

The expected [App\Mail\MyEmail] mailable was not queued.Failed asserting that false is true.

That's if you simply return true or false in the callback version. Note that you can use asserts in the callback, which is great, it's just more awkward if you need to check more than one email.