Code sur écran d'ordinateur

PHPunit: How to test a controller which throws an error.

Let’s say we have a method in a controller like this:

/**
'@Route (path'/add', name'"add," methods
*/
public function add (Request $request,): Response 
{
   throw new BadRequestHttpException ('Error');
}

To test that the exception is properly thrown, just write this

public function testList(: void
{
   $this->expectException(BadRequestHttpException::class);
   $client = self::createClient();
   $client->catchExceptions (false);
   $crawler = $client->request (
      Request::METHOD_POST,
      '/add'
   );
}

The first function expectException indicates to phpunit that the method will throw an error.

The second one catchExceptions prevents the exception from being displayed on the terminal during testing

Testing Project Test Suite
..[error] Uncaught PHP Exception Symfony-Component-HttpKernel-Exception-BadRequestHttpException:...

So the rest of the tests will not be interrupted.

Leave a comment