0
votes

I'm trying to write a Laravel PHPUnit test that checks if a mail has been queued after a user was created.

<?php

namespace Tests\Unit\User;

use App\User;
use Tests\TestCase;
use App\Notifications\UserCreated;
use Illuminate\Support\Facades\Mail;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Support\Facades\Notification;
use Illuminate\Foundation\Testing\RefreshDatabase;

class UserUnitTest extends TestCase
{
    use RefreshDatabase;

    /**
     * check if a user was created in database
     *
     * @return void
     */
    public function testUserCreate()
    {
        $user = factory(User::class)->create();

        $this->assertDatabaseHas('users', [
            'email'             => $user->email,
            'active'            => 0,
            'activation_token'  => $user->activation_token,
            'deleted_at'        => NULL
        ]);
    }

    /**
     * check if email was sent after user was created in database
     *
     * @return void
     */
    public function testEmailSentAfterUserCreated()
    {
        Notification::fake();

        // Assert that no notifications were sent...
        Notification::assertNothingSent();

        $user = factory(User::class)->create();

        // Assert a notification was sent to the given users...
        Mail::assertQueued(UserCreated::class, 1);
    }
}

When I run this test testEmailSentAfterUserCreated it throws the following exception.

There was 1 error:

1) Tests\Unit\User\UserUnitTest::testEmailSentAfterUserCreated BadMethodCallException: Method Illuminate\Mail\Mailer::assertQueued does not exist.

/home/vagrant/Projects/endiro/vendor/laravel/framework/src/Illuminate/Support/Traits/Macroable.php:103 /home/vagrant/Projects/endiro/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:245 /home/vagrant/Projects/endiro/tests/Unit/User/UserUnitTest.php:49

The Mail class has been included and I'm sure the arguments are correct but I'm not sure why I'm getting this error.

2
Did my answer help or what are the problems you are facing?mrhn

2 Answers

1
votes

Use Mail::fake() if you want to assert on Mail::assertQueued(). I was facing the same issue. I forgot to add Mail::fake() in that particular test case.

0
votes

Notifications does not have an assert queued, it has an assertSentTo().So an example of how it should look. If the notification can be queued, i would think you could use the Queue::fake() to achieve this.

Notification::assertSentTo(
    [$user], UserCreated::class
);