deepu07's avatar
Level 11

How to test Email mock in laravel.

Here I'm trying to send a mail who are not registered within last date. When I'm trying to run this test case It is skipping email assertions and executing last assertion. Can you guys help me out on this? Thanks In advance. (Assume Last date is yesterday)

    ```$msg = [
        'subject' => 'mail subject',
        'body' => 'mail body',
        'username' => '[email protected]'
    ];

    $lateRegister = Register::where('last_date', '<=', \Carbon\Carbon::now())->get();

    if(count($lateRegister) == 0){
        $mock = Mockery::mock('Swift_Mailer');
        $this->app['mailer']->setSwiftMailer($mock);
        $mock->shouldReceive('send')->once
             ->andReturnUsing(function($msg)
         {
            $this->assertEquals('mail subject', $msg['subject'], 'Subject was not sent');
            $this->assertEquals('[email protected]', $msg['username'], 'From Email id ');
            $this->assertContains('mail body', $msg['body'], 'Im from email body');
        });
    }
    $this->assertTrue(count($lateRegister) != 0);
}```
0 likes
4 replies
skliche's avatar

@deepu07 Is that block of code even executed, does count($lateRegister) == 0 return true?

Why don't you use the Mail Fake?

deepu07's avatar
Level 11

@skliche How to do with Mail Fake ?? And also I have this logic in my observer. How to accomplish this guy?

skliche's avatar

@deepu07 Something like this

Mail::fake();

$lateRegister = Register::where('last_date', '<=', \Carbon\Carbon::now())->get();

$this->assertTrue(count($lateRegister) > 0);

Mail::assertSent(YourMailable::class, function($mail) {
    $mail->build();

    return $mail->hasFrom('[email protected]') && $mail->subject === 'mail subject';
}
deepu07's avatar
Level 11

@skliche does it make sense?

public function testEmail()
    {
        $txt = [ 'subject' => ' New comment  was added', 'username' => '[email protected]' ];
        $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']);
     }```

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?

Please or to participate in this conversation.