PHPUnit – How to test a controller that 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={“POST”}) */ 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’ ); … Read more

PHPUnit – Set a protected or private property on a mock

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’) ->disableOriginalConstructor() ->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 mock an object and its 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 product is a … Read more