3 namespace Drupal\Tests\Core\EventSubscriber;
5 use Drupal\Core\Cache\CacheableJsonResponse;
6 use Drupal\Core\Cache\CacheableMetadata;
7 use Drupal\Core\EventSubscriber\ExceptionJsonSubscriber;
8 use Drupal\Core\Http\Exception\CacheableMethodNotAllowedHttpException;
9 use Drupal\Tests\UnitTestCase;
10 use Symfony\Component\HttpFoundation\JsonResponse;
11 use Symfony\Component\HttpFoundation\Request;
12 use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
13 use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
14 use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
15 use Symfony\Component\HttpKernel\HttpKernelInterface;
18 * @coversDefaultClass \Drupal\Core\EventSubscriber\ExceptionJsonSubscriber
19 * @group EventSubscriber
21 class ExceptionJsonSubscriberTest extends UnitTestCase {
25 * @dataProvider providerTestOn4xx
27 public function testOn4xx(HttpExceptionInterface $exception, $expected_response_class) {
28 $kernel = $this->prophesize(HttpKernelInterface::class);
29 $request = Request::create('/test');
30 $event = new GetResponseForExceptionEvent($kernel->reveal(), $request, 'GET', $exception);
31 $subscriber = new ExceptionJsonSubscriber();
32 $subscriber->on4xx($event);
33 $response = $event->getResponse();
35 $this->assertInstanceOf($expected_response_class, $response);
36 $this->assertEquals('{"message":"test message"}', $response->getContent());
37 $this->assertEquals(405, $response->getStatusCode());
38 $this->assertEquals('POST, PUT', $response->headers->get('Allow'));
39 $this->assertEquals('application/json', $response->headers->get('Content-Type'));
42 public function providerTestOn4xx() {
44 'uncacheable exception' => [
45 new MethodNotAllowedHttpException(['POST', 'PUT'], 'test message'),
48 'cacheable exception' => [
49 new CacheableMethodNotAllowedHttpException((new CacheableMetadata())->setCacheContexts(['route']), ['POST', 'PUT'], 'test message'),
50 CacheableJsonResponse::class