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

Code sur écran d'ordinateur

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 ( … Read more

PhpUnit – mock – internal set protected / private variable

MacBook avec code sur un bureau

Using mocks it is often necessary to give a value to a private or protected variable. To do this, just use the Reflection class. $basket – $this–getMockBuilder ('Basket') OriginalConstructor() -getMock(; $basketReflection – new ReflectionClass ($basket); $sessionId – $basketReflection–getProperty ('sessionId'); $sessionId-setAccessible (true); $sessionId-setValue ($basket, 'abc'); so the sessionId value in our Mock will be ‘abc’.

PHPUnit how to mocker / simulate an object and methods

Code sur écran d'ordinateur

When you start using PHPUnit, you often find yourself facing the need to simulate a method or object. Fortunately PHPUnit has some methods that can be very useful. How to simulate an object The easiest way to create a mocked object $product – $this–getMockBuilder (‘Product’) -getMock(; or $product – $this–getMockBuilder (‘Product’) -setMethods (array)) -getMock(; This … Read more