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 well lifted 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 return an error.
Publicités
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 points will not be interrupted.
Publicités