Laravel unit testing emails

前端 未结 8 1563
难免孤独
难免孤独 2021-02-20 10:12

My system sends a couple of important emails. What is the best way to unit test that?

I see you can put it in pretend mode and it goes in the log. Is there something t

8条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-20 10:51

    If you want to test everything around the email, use

    Mail::fake()
    

    But if you want to test your Illuminate\Mail\Mailable and the blade, then follow this example. Say, you want to test a Reminder email about some payment, where the email text should have product called 'valorant' and some price in 'USD'.

     public function test_PaymentReminder(): void
    {
        /* @var $payment SalePayment */
        $payment = factory(SalePayment::class)->create();
        auth()->logout();
    
        $paymentReminder = new PaymentReminder($payment);
        $html            = $paymentReminder->render();
    
        $this->assertTrue(strpos($html, 'valorant') !== false);
        $this->assertTrue(strpos($html, 'USD') !== false);
    }
    

    The important part here is ->render() - that is how you make Illuminate\Mail\Mailable to run build() function and process the blade.

    Another importan thing is auth()->logout(); - because normally emails being processed in a queue that run in a background environment. This environment has no user and has no request with no URL and no IP...

    So you must be sure that you are rendering the email in your unit test in a similar environment as in production.

提交回复
热议问题