Laravel单元测试电子邮件

T3c*_*rat 9 php laravel laravel-4

我的系统发送了几封重要的电子邮件.单元测试的最佳方法是什么?

我看到你可以把它放在假装模式,它会在日志中.有什么东西要检查吗?

Lau*_*nce 10

有两种选择.

选项1 - 模拟邮件外观以测试邮件是否正在发送.像这样的东西会起作用:

$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());
    });
Run Code Online (Sandbox Code Playgroud)

选项2更容易 - 它是使用MailCatcher.me测试实际的SMTP .基本上,您可以发送SMTP电子邮件,并"测试" 实际发送的电子邮件.Laracasts在如此使用它作为Laravel测试的一部分方面有很好的教训.


hap*_*set 6

“@The Shift Exchange”中的“选项 1”在 Laravel 5.1 中不起作用,因此这里是使用 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(['foo@bar.com' => null], $message->getTo());
        $this->assertContains('Some string', $message->getBody());
        return true;
    }), \Mockery::any()])
    ->once();
Run Code Online (Sandbox Code Playgroud)


Sla*_*a V 6

对于 Laravel 5.4 检查Mail::fake()https : //laravel.com/docs/5.4/mocking#mail-fake