Laravel unit testing emails

前端 未结 8 1382
难免孤独
难免孤独 2021-02-20 10:12

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 t

8条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-20 10:38

    There are two options.

    Option 1 - Mock the mail facade to test the mail is being sent. Something like this would work:

    $mock = Mockery::mock('Swift_Mailer');
    $this->app['mailer']->setSwiftMailer($mock);
    $mock->shouldReceive('send')->once()
        ->andReturnUsing(function($msg) {
            $this->assertEquals('My subject', $msg->getSubject());
            $this->assertEquals('foo@bar.com', $msg->getTo());
            $this->assertContains('Some string', $msg->getBody());
        });
    

    Option 2 is much easier - it is to test the actual SMTP using MailCatcher.me. Basically you can send SMTP emails, and 'test' the email that is actually sent. Laracasts has a great lesson on how to use it as part of your Laravel testing here.

提交回复
热议问题