Asserting exceptions in PEST

Asserting exceptions in PEST

In case you didn't notice, recently I have been working in a secret project called Pest: an elegant PHP Testing Framework with a focus on simplicity.

Pest is under works, and it will be out soon! I've put together a website where you can subscribe to the @pestphp newsletter. Join now, and be the first to get news about this project: pestphp.com.

In this article, we are going to check how can you assert that a specific exception was thrown in your test.

In Pest, the given closure to test functions is always bound to a specific PHPUnit test case class. By default, that class is PHPUnit\Framework\TestCase. So, as usual, you can use $this->expectException and $this->expectExceptionMessage.

<?php

it('rejects invalid requests', function () {
    $this->expectException(Exception::class);
    $this->expectExceptionMessage('foo');

    throw new Exception('foo');
});

Now, Pest also offers you a second way of asserting that a specific exception was thrown, using the method throws. Let's take a look:

<?php

it('rejects invalid requests', function () {
    throw new Exception('foo');
})->throws(Exception::class);

And, of course, if you also want to assert the exception message, you just have to pass the message as the second argument of the method throws.

<?php

it('rejects invalid requests', function () {
    throw new Exception('foo');
})->throws(Exception::class, 'foo');

Hope you like this article. Stay tuned: the early beta version will be out soon: pestphp.com.

Show Comments