在测试中,我想使用以下方法对 Mailable 做出一些断言Mail::assertSent()
, 像这样:
Mail::assertSent(MyMailable::class, function ($mail) use ($user) {
return $mail->hasTo($user->email);
});
到目前为止,我已经找到了hasTo()
, hasFrom()
, hasBcc()
和所有其他的has*()
方法效果很好。但是,当断言 Mailable 存在特定属性时,例如subject
该属性显示为 null 并且断言失败:
Mail::assertSent(MyMailable::class, function ($mail) {
return $mail->subject === 'My Subject';
});
我相信这是因为我已经配置了所有可邮寄属性build()
在断言阶段可能尚未调用该方法,因此尚未在对象上设置属性。
我想使用build()
方法是根据文档采取的正确方法:
可邮寄类的所有配置都是在构建方法中完成的。在此方法中,您可以调用各种方法(例如 from、subject、view 和 Attach)来配置电子邮件的呈现和传递。
https://laravel.com/docs/5.5/mail#writing-mailables https://laravel.com/docs/5.5/mail#writing-mailables
我发现当我在构造函数上设置属性时,我可以获得 Mailable 属性的断言:
class MyMail extends Mailable
{
public function __construct()
{
$this->subject = 'My Subject';
}
public function build() {
return $this->subject('My Subject')->view('emails/my-email')
}
}
但是,我觉得这种方法是错误的,因为我觉得我正在更改代码以适应我的测试。
所以,我想知道是否有更好的方法来对 Mailable 上的属性进行断言?任何帮助将不胜感激,谢谢!
EDIT 1
测试类(去掉无关代码)
/** @test */
function a_notification_is_sent_when_an_application_is_updated()
{
Mail::fake([RequiresVerification::class]);
// some set up and factory methods called here...
// the listener for this event sends mail
ApplicationUpdated::dispatch($application);
// this assertion passes
Mail::assertSent(RequiresVerification::class);
// this assertion does not pass when subject is set on the build()
// method but passes when subject is set on the constructor
Mail::assertSent(RequiresVerification::class, function ($mail) use ($user) {
return $mail->subject === 'hello';
});
}
EDIT 2
我目前正在查看hasRecipient() method https://github.com/laravel/framework/blob/5.5/src/Illuminate/Mail/Mailable.php#L540,其中所有has*
方法使用,看看它如何处理针对我假设的可邮寄属性(to、from、bcc、cc 等)进行断言。也许可以使用类似的方法扩展 Mailable 对象以添加新的属性断言?
https://github.com/laravel/framework/blob/5.5/src/Illuminate/Mail/Mailable.php#L540 https://github.com/laravel/framework/blob/5.5/src/Illuminate/Mail/Mailable.php#L540