Exceptions & Errors

Overview

Testing the behavior in PHP sometimes requires checking if an exception/error was thrown.

Writing a test to expect a test to throw an exception can be done as follows:

1it('throws exception', function () {
2 throw new Exception('Something happened.');
3})->throws(Exception::class);

If you wish to assert the exception message too, you need to give a second argument to the throws method:

1it('throws exception', function () {
2 throw new Exception('Something happened.');
3})->throws(Exception::class, 'Something happened.');

If you're only interested in the message, and the exception type isn't important, you can just provide the message by itself:

1it('throws exception', function () {
2 throw new Exception('Something happened.');
3})->throws('Something happened.');

Next section: Groups Of Tests →