deepu07's avatar
Level 11

PHP Unit Testing (Mail)

public function testEmail() { $txt = [ 'subject' => ' New comment was added', 'username' => 'user123@mail.com' ]; $parameters = [ 'description' => 'this is comment' ];

    \Mail::shouldReceive('send')
        ->once()
        ->andReturnUsing();

      $this->call('POST', '/api/post/{post_id}/comment', $parameters)->original;
      $this->assertEquals('[email protected]', $msg['username']);
 }```

above code make sense?? Here I'm trying to send an email when someone commented on post. I do have an observer for that mail thing. How to write a test script for this? Can you help me out? Thanks in advance!

0 likes
1 reply
bobbybouwmann's avatar
Level 88

Well in that case are you trying to mock the mail call, however you should check if the email was send or not. In Laravel you can do that like so:

public function testEmail()
{
    Mail::fake();
    
    // Your post call here

    Mail::assertSent(CommentPosted::class); // This is a mailable class

    // You can also check if the correct email was send 
    // by checking the data that was send to it
    Mail::assertSent(CommentPosted::class, function ($mail) use ($user) {
        return $mail->hasTo($user->email) &&
            $mail->hasCc('...') &&
            $mail->hasBcc('...');
    });
}
 

Documentation: https://laravel.com/docs/5.5/mocking#mail-fake

1 like

Please or to participate in this conversation.