framework: [5.1] Testing “failed” requests

I’m not sure where this problem comes from, if it’s PHPUnit, the web crawler, Symfony or Laravel. There also might be a better way of testing this kind of thing - if someone could point me to it that would be great!

That said, here’s what I’m trying to achieve:

I have a route which for whatever reason is unauthorized:

Route::get('/test', function () {
    abort(403);
});

I have the following test to make sure it is indeed inaccessible:

/**
 * You shall not pass!
 *
 * @expectedException Symfony\Component\HttpKernel\Exception\HttpException
 */
public function testUnauthorizedRoute()
{
    $this->visit('/test');
}

However, when I run phpunit, the exception is not caught as per the @expectedException annotation… I get the following error message instead:

There was 1 failure:

1) ExampleTest::testUnauthorizedRoute
A request to [http://localhost/test] failed. Received status code [403].

/Users/Wayne/source/laravel-test/vendor/laravel/framework/src/Illuminate/Foundation/Testing/CrawlerTrait.php:259
/Users/Wayne/source/laravel-test/vendor/laravel/framework/src/Illuminate/Foundation/Testing/CrawlerTrait.php:177
/Users/Wayne/source/laravel-test/vendor/laravel/framework/src/Illuminate/Foundation/Testing/CrawlerTrait.php:59
/Users/Wayne/source/laravel-test/tests/ExampleTest.php:12
phar:///usr/local/bin/phpunit/phpunit/TextUI/Command.php:176
phar:///usr/local/bin/phpunit/phpunit/TextUI/Command.php:129

Caused by
exception 'Symfony\Component\HttpKernel\Exception\HttpException' in /Users/Wayne/source/laravel-test/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:882

I do currently have a workaround, the actual exception thrown is an instance of PHPUnit_Framework_ExpectationFailedException, so I just catch it and check the message:

try {
    $this->visit('/test');
} catch (\Exception $err) {
    $this->assertContains('Received status code [403]', $err->getMessage());
}

For posterity’s sake, I’ve created a test repo over at https://github.com/wayneashleyberry/laravel-test

You can replicate this issue by following these commands:

git clone git@github.com:wayneashleyberry/laravel-test.git
cd laravel-test
cp .env.example .env
composer install
php artisan key:generate
vendor/bin/phpunit

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 15 (7 by maintainers)

Most upvoted comments

Yes, there are other methods other than visit that do throw the http exception, as I said. Use them.