1 回答

TA貢獻1871條經驗 獲得超13個贊
看起來MailChannel
發送通知電子郵件的驅動程序沒有使用Mail
外觀,這意味著Mail::fake
不會影響它。相反,它直接調用該send
方法,該方法又調用(郵件驅動程序)。Mailable
send
Mailer
您可以將Mailable
實例替換為MailFake
(這是Mail::fake
使用的)的實例,但它看起來MailFake
不適合當$view
是一個數組(這是MailChannel
傳遞給 的內容Mailable
)的情況。
幸運的是,Laravel 源代碼包含一個示例,說明他們如何測試在SendingMailNotificationsTest
. 他們模擬Mailer
andMarkdown
實例并檢查傳遞的參數。你可以做類似的事情:
use Mockery as m;
use Illuminate\Contracts\Mail\Mailable;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Mail\Markdown;
use Illuminate\Mail\Message;
class ContactFormTest extends TestCase
{
protected function tearDown(): void
{
parent::tearDown();
m::close();
}
protected function setUp(): void
{
parent::setUp();
$this->mailer = m::mock(Mailer::class);
$this->markdown = m::mock(Markdown::class);
$this->instance(Mailer::class, $this->mailer);
$this->instance(Mailer::class, $this->markdown);
}
public function a_mail_is_send_when_the_contact_form_is_used()
{
$this->withExceptionHandling();
$user = factory(User::class)->create();
$this->markdown->shouldReceive('render')->once()->andReturn('htmlContent');
$this->markdown->shouldReceive('renderText')->once()->andReturn('textContent');
$data = [
'name' => 'John Doe',
'email' => '[email protected]',
'message' => 'This is a test message'
];
$notification = new ContactRequestNotification($data);
$this->mailer->shouldReceive('send')->once()->with(
['html' => 'htmlContent', 'text' => 'textContent'],
array_merge($notification->toMail($user)->toArray(), [
'__laravel_notification' => get_class($notification),
'__laravel_notification_queued' => false,
]),
m::on(function ($closure) {
$message = m::mock(Message::class);
$message->shouldReceive('to')->once()->with([$user->email]);
$closure($message);
return true;
})
);
$response = $this->post('/contact', $data);
$response->assertStatus(200);
}
}
就個人而言,我現在寧愿只toMail對類上的方法進行單元測試,ContactRequestNotification因為我認為上面的方法不是很漂亮。
- 1 回答
- 0 關注
- 194 瀏覽
添加回答
舉報