Ad

How Can I Test Mail Sending Using Phpunit?

- 1 answer

I have a mailable class which I use to send an email to users, which works fine. I want to write some phpunit test to check if the mail is actually sent. Unfortunately, I couldn't find a good explanation in the documentation.

My mailable class:

class UserInvite extends Mailable
{
    use Queueable, SerializesModels;

    public $user;
    public $inviteMessage;

    /**
     * Create a new message instance.
     *
     * @param User $user
     * @param string $inviteMessage
     */
    public function __construct(User $user, string $inviteMessage)
    {
        $this->user = $user;
        $this->inviteMessage = $inviteMessage;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('emails.mail');
    }
}

Test:

/** @test */
public function it_sends_invite()
{
    Mail::fake();
    $user = factory(User::class)->create();
    $inviteMessage = 'test';

    Mail::assertSent(new UserInvite($user, $inviteMessage));
}

Error:

ErrorException: Object of class App\Mail\UserInvite could not be converted to string

Solution:

/** @test */
    public function it_sends_invite()
    {
        Mail::fake();

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

        Mail::to($user)->send(new UserInvite($user, 'message'));

        Mail::assertSent(UserInvite::class);
    }
Ad

Answer

When testing for sent mails, you don't pass a whole mailable instance. PHPUnit wouldn't be able to compare a full object anyway. Instead, you just pass the fully qualified class name:

// use App\Mail\UserInvite;

Mail::assertSent(UserInvite::class);
Ad
source: stackoverflow.com
Ad