php - 如何测试使用字符串正文发送的 Laravel 邮件,而不是使用 Mailable

标签 php laravel testing phpunit laravel-6

我有这封邮件发送出去

Mail::send([], [], function ($message) use ($email) {
    $message->to($email->to)
        ->subject($email->subject)
        ->setBody($email->content, 'text/html');
});

我如何断言此邮件是在测试中发送的?

使用 Mail::fake() 门面,但是 Mail::assertSent() 需要一个字符串 Mailable。

欢迎任何建议。

最佳答案

默认情况下,PHPUnit 使用array 邮件驱动程序并将所有发送的邮件存储在一个数组中。

因此,一种选择是放弃 Mail::fake(),在测试中触发电子邮件,然后检查消息数组。

我在测试中使用的自定义断言:

protected function assertMailSentTo($user, $times = 1)
{
    // resolves the mail driver and gets messages
    $messages = app('swift.transport')->messages();

    $filtered = $messages->filter(function ($message) use ($user) {
        return array_key_exists($user->email, $message->getTo());
    });

    $expected = $times;

    $actual = $filtered->count();

    $this->assertTrue(
        $expected === $actual,
        "Sent {$actual} messages instead of {$expected}."
    );
}

关于php - 如何测试使用字符串正文发送的 Laravel 邮件,而不是使用 Mailable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58855488/

相关文章:

php - 如何解压 txt.gz 文件并使用 php 存储到数据库中

c++ - 如何使用 Boost.Test 对跳过的测试进行硬编码?

php - Laravel 验证器响应嵌套数组

node.js - Mocha : How to test Express rendered views

python - Django manage.py 测试

php - 来自实体的 Doctrine 2 更新

c# - 创建一个 Youtube 机器人

php - ZF2 - 如何正确设置标题?

Laravel url 先前在页面重新加载后返回同一页面

php - 为什么在 Laravel AuthController 中重写 postRegister 不起作用?