Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel unit testing emails

My system sends a couple of important emails. What is the best way to unit test that?

I see you can put it in pretend mode and it goes in the log. Is there something to check that?

like image 517
T3chn0crat Avatar asked Aug 09 '14 20:08

T3chn0crat


People also ask

How to test Notifications Laravel?

There are two ways you can use to test the email contents of a Laravel notification. The first way is to ensure that the notification was actually sent. After sending it, you can inspect the contents of the email that was sent. The second way would be to write a unit Test for this specific notification.

How can we check email sent or not in Laravel?

wrap it in a try catch instead, if exception not caught email is sent, otherwise it failed, try { Mail::to($userEmail)->send($welcomeMailable); } catch (Exception $e) { //Email sent failed. }

Why is unit testing so hard?

Developers experience Unit Testing as difficult when they run into these kinds of problems: Classes are tightly coupled to other classes, which makes it hard to test because you need to control those other classes as well when you are writing your tests. This is very, very difficult and very error prone.

What is mocking Laravel?

When testing Laravel applications, you may wish to "mock" certain aspects of your application so they are not actually executed during a given test. For example, when testing a controller that dispatches an event, you may wish to mock the event listeners so they are not actually executed during the test.


1 Answers

"Option 1" from "@The Shift Exchange" is not working in Laravel 5.1, so here is modified version using Proxied Partial Mock:

$mock = \Mockery::mock($this->app['mailer']->getSwiftMailer());
$this->app['mailer']->setSwiftMailer($mock);
$mock
    ->shouldReceive('send')
    ->withArgs([\Mockery::on(function($message)
    {
        $this->assertEquals('My subject', $message->getSubject());
        $this->assertSame(['[email protected]' => null], $message->getTo());
        $this->assertContains('Some string', $message->getBody());
        return true;
    }), \Mockery::any()])
    ->once();
like image 178
happy_marmoset Avatar answered Oct 31 '22 05:10

happy_marmoset