【问题标题】:Behat functional test stop Symfony HttpKernal redirectsBehat 功能测试停止 Symfony HttpKernal 重定向
【发布时间】:2020-11-11 19:55:00
【问题描述】:

我正在使用 Behat 测试我的团队开发的 REST API。创建特定资源时,API 会在响应中返回 201 和 Location 标头。

API 是使用 Symfony5 开发的,它使用 Symfony HttpKernel 作为客户端:

$kernel->handle($request);

我想通过我的行为测试断言它返回 201 并且标头包含位置。但是客户端会自动跟踪 Location 标头,因此我无法验证。

有没有办法使用现有的内核组件关闭以下重定向?我一直无法找到一种方法来做到这一点。

【问题讨论】:

    标签: rest functional-testing behat symfony5


    【解决方案1】:

    您可以创建自己的上下文并检查响应

    <?php declare(strict_types=1);
    
    namespace App\Tests\Features\Context;
    
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\HttpFoundation\Response;
    use Symfony\Component\HttpKernel\Kernel;
    
    final class HttpContext
    {
        private Kernel $kernel;
        private Response $response;
    
        public function __construct(Kernel $kernel)
        {
            $this->kernel = $kernel;
        }
    
        /**
         * @When I request :method to :uri
         */
        public function iRequest(string $method, string $uri): void
        {
            $this->request($method, $uri);
        }
    
        /**
         * @Then the location header should be :location
         */
        public function assertLocationHeader(string $location): void
        {
            // make your assertion
            dd($this->response->headers->get('location'), $location);
        }
    
        private function request(string $method, string $uri): void
        {
            $request = Request::create($uri, $method, [], [], [], [], null);
    
            $this->response = $this->kernel->handle($request);
    
            $this->kernel->terminate($request, $this->response);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-04-02
      • 2016-08-20
      • 1970-01-01
      • 1970-01-01
      • 2021-02-06
      • 1970-01-01
      • 2014-05-16
      • 2018-01-22
      • 1970-01-01
      相关资源
      最近更新 更多