2021年3月20日星期六

Overriding the Request and Testing

I have an issue with extending the default Request class from Symfony and writing unit tests.

I set a request factory in index.php after that set some properties to the custom Request in a RequestListener and it works fine, but when I run a test class, it breaks.

Here is the index.php:

<?php    use App\Kernel;  use Symfony\Component\Dotenv\Dotenv;  use Symfony\Component\ErrorHandler\Debug;  use Symfony\Component\HttpFoundation\Request;    require dirname(__DIR__).'/vendor/autoload.php';    (new Dotenv())->bootEnv(dirname(__DIR__).'/.env');    if ($_SERVER['APP_DEBUG']) {      umask(0000);        Debug::enable();  }    $kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);  Request::setFactory(function (array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null) {      return new \App\Extension\HttpFoundationExtension\Request($query, $request, $attributes, $cookies, $files, $server, $content);  });  $request = Request::createFromGlobals();  $response = $kernel->handle($request);  $response->send();  $kernel->terminate($request, $response);  

Here is also the test class:

<?php    namespace App\Tests\Api;    use ApiPlatform\Core\Bridge\Symfony\Bundle\Test\ApiTestCase;    class AccountTest extends ApiTestCase  {      public function testGetCollection(): void      {          $response = static::createClient()->request("GET", "/accounts");          self::assertResponseStatusCodeSame(201);      }  }  

I don't know why, but if I extend the WebTestCase and not the ApiTestCase class from the test, the index.php is started.


I found the following info in Symfony docs, but I don't know how this can help me. :)

To run your functional tests, the WebTestCase class needs to know which is the application kernel to bootstrap it. The kernel class is usually defined in the KERNEL_CLASS environment variable (included in the default .env.test file provided by Symfony): If your use case is more complex, you can also override the createKernel() or getKernelClass() methods of your functional test, which take precedence over the KERNEL_CLASS env var.



Here are some useful links I found on this topic:
  • Testing and the Kernel: Click here to view
  • Overriding the Request: Click here to view

Thanks!

https://stackoverflow.com/questions/66715130/overriding-the-request-and-testing March 20, 2021 at 04:22AM

没有评论:

发表评论