Search code examples
phplaraveltestingmockinglaravel-5.5

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


I have a few laravel commands that inherit from my own class to send slack messages if they fail. However if the slack notification fails I still want the original exception thrown so that the error still ends up in the logs if slack is unavailable or misconfigured. I have this and it works, but I can't figure out how to trigger an exception in the Notification part in tests.

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()
            );
        }
    }
}

As Notification::route is defined on the facade I can't use Notification::shouldReceive to trigger the exception and the SlackNotification is newed up making it difficult to mock.

Any ideas as to how I can trigger an exception?


Solution

  • If anybody's still wondering how to do this, you can mock Notification::send like:

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