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?
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.
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. }
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.
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.
"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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With