Laravel 当测试 Maillable hasFrom(...) 方法时,PHPUnit 得到 "ErrorException: Illegal string offset 'address' "

Laravel PHPUnit gets "ErrorException: Illegal string offset 'address' " when testnig Maillable hasFrom(...) method

这是我的 Mailable class:

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class OrderConfirmation extends Mailable
{
    use Queueable, SerializesModels;

    public $message;
    public $subject;
    public $from;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($message, $subject, $from)
    {
        $this->message = $message;
        $this->subject = $subject;
        $this->from = $from;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->from($this->from)
            ->subject($this->subject)
            ->view('emails.orders.confirmation');
    }
}

我正在尝试检查邮件是否具有特定的发件人地址,如下所示:

Mail::fake();
$customer = 'test@test.com';
$from = 'from@test.com';
Mail::to($customer)->queue(new OrderConfirmation('Some Message', 'Some Subject', $from));

Mail::assertQueued(OrderConfirmation::class, function ($mail) {
     return $mail->hasFrom('from@test.com');
});

但它得到 "ErrorException: Illegal string offset 'address' "

/var/www/vendor/laravel/framework/src/Illuminate/Mail/Mailable.php:597

Laravel 5.6

是bug还是我做错了什么?

您遇到此问题的原因是您覆盖了 Mailable class 中的 $from 属性。

您可以删除在 class 中设置的 $from 属性 并从构造函数中调用 from() 方法:

public $message;

public function __construct($message, $subject, $from)
{
    $this->message = $message;
    $this->subject = $subject;
    $this->from($from);
}

public function build()
{
    return $this->view('emails.orders.confirmation');
}

或者,您可以将 $from 属性 重命名为 $fromAddress

NB subject 也发生了同样的情况,但是由于 subject() 方法只是为主题赋值 属性 在 class 上实际上并没有引起问题。