Exceptions

When testing behavior in PHP, you might need to check if an exception or error has been thrown. To create a test that expects an exception to be thrown, you can use the throws() method.

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

If you also want to make an assertion against the exception message, you may provide a second argument to the throws() method.

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

If the exception type is not relevant, and you're only concerned with the message, you can simply pass the message without specifying the exception's type.

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

You can use the throwsIf() method to conditionally verify an exception if a given boolean expression evaluates to true.

1it('throws exception', function () {
2 //
3})->throwsIf(fn() => DB::getDriverName() === 'mysql', Exception::class, 'MySQL is not supported.');

Just like throwsIf() method, you can use the throwsUnless() method to conditionally verify an exception if a given boolean expression evaluates to false.

1it('throws exception', function () {
2 //
3})->throwsUnless(fn() => DB::getDriverName() === 'mysql', Exception::class, 'Only MySQL is supported.');

You can also verify that a given closure throws one or more exceptions using the toThrow() method of the expectation API.

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

If you expect no exceptions to be thrown, you can use the throwsNoExceptions() method.

1it('throws no exceptions', function () {
2 $result = 1 + 1;
3})->throwsNoExceptions();

Sometimes, you may want to simply mark a test as failed. You can use the fail() method to do so.

1it('fail', function () {
2 $this->fail();
3});

You may also provide a message to the fail() method.

1it('fail', function () {
2 $this->fail('Something went wrong.');
3});

In addition, you can also use the fails() method to verify the test fails.

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

Just like the fail() method, you may also provide a message to the fails() method.

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

After learning how to write tests that assert exceptions, the next step is to explore "Test Filtering". This feature allows you to efficiently run specific tests based on criteria like test name, dirty files, and more: Filtering Tests →