如何使 Laravel 的通知在测试中抛出异常

How to make Laravel's Notification throw an Exception in test

我有几个 laravel 命令继承自我自己的 class,用于在失败时发送松弛消息。但是,如果 slack 通知失败,我仍然希望抛出原始异常,以便在 slack 不可用或配置错误时错误仍会出现在日志中。我有这个并且它可以工作,但我不知道如何在测试的通知部分触发异常。

namespace App\Support;

use App\Notifications\SlackNotification;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Notification;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class CarrotCommand extends Command
{   
    protected function execute(InputInterface $input, OutputInterface $output)                  
    {
        try {
            return parent::execute($input, $output);
        } catch (\Exception $e) {
            $this->notifySlack($e);

            throw $e;
        }
    }


    protected function notifySlack(\Exception $e)
    {
        try {
            Notification::route('slack', config('app.slack_webhook'))->notify(
                new SlackNotification(
                    "Error\n" . get_class($e) . ': ' . $e->getMessage(),
                    'warning'
                )
            ); 
        } catch (\Exception $exception) {

            // I want to reach this part in a test

            $this->error(
                'Failed to send notice to slack: ' . $exception->getMessage()
            );
        }
    }
}

由于 Notification::route 是在 facade 上定义的,我不能使用 Notification::shouldReceive 来触发异常,并且 SlackNotification 是新的,因此很难模拟。

关于如何触发异常有什么想法吗?

如果有人仍然想知道如何做到这一点,您可以模拟 Notification::send,例如:

Notification::shouldReceive('send')
  ->once()
  ->andThrow(new \Exception());