首页 > 解决方案 > Behat 功能测试停止 Symfony HttpKernal 重定向

问题描述

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

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

$kernel->handle($request);

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

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

标签: restfunctional-testingbehatsymfony5

解决方案


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

<?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);
    }
}

推荐阅读