rest - Behat 功能测试停止 Symfony HttpKernal 重定向
问题描述
我正在使用 Behat 测试我的团队开发的 REST API。创建特定资源时,API 会在响应中返回 201 和 Location 标头。
API 是使用 Symfony5 开发的,它使用 Symfony HttpKernel 作为客户端:
$kernel->handle($request);
我想通过我的行为测试断言它返回 201 并且标题包含位置。但是,客户端会自动遵循 Location 标头,因此我无法验证这一点。
有没有办法使用现有的内核组件关闭以下重定向?我一直无法找到一种方法来做到这一点。
解决方案
您可以创建自己的上下文并检查响应
<?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);
}
}
推荐阅读
- sql-server - 服务主密钥解密期间发生创建凭据错误
- netlify-cms - 如何在 Netlify CMS 中添加图片上传功能
- optaplanner - Optaplanner ScoreDirector 持续规划 DayOff 请求
- image-processing - 我们如何在 CNN 中选择内核?(卷积神经网络)
- ajax - 将 2 个表单放在同一页面上的最佳方法是什么?
- android - 广播接收器未收到 USB 权限
- r - 绘制 PCA,autoplot() 不会按组变量分隔颜色
- url - url中的“?ac_id = 2”是什么意思?
- c# - 在每个派生类构造函数之后调用方法
- java - 尝试解析 JSONArray 时出现 ClassCastException