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 AppSupport; use AppNotificationsSlackNotification; use IlluminateConsoleCommand; use IlluminateSupportFacadesNotification; use SymfonyComponentConsoleInputInputInterface; use SymfonyComponentConsoleOutputOutputInterface; 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( "Errorn" . 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?
Advertisement
Answer
If anybody’s still wondering how to do this, you can mock Notification::send
like:
Notification::shouldReceive('send') ->once() ->andThrow(new Exception());