php - KernelBrowser 将参数添加到正文 POST 请求
问题描述
我正在尝试使用 phpunit 和 symfony WebTestCase 对象测试我的 Api 的端点。我必须使用 KernelBrowser 发送一个 POST 请求,但我不知道如何将参数添加到请求的正文中。我的请求在邮递员上工作得很好。
我试过这个
$client->request('POST', '/url', ['param1' =>'value1', 'param2' => 'value2']);
它不工作。
我试过这个
$client->request('POST', '/url', [], [], [], '{param1: value, param2: value}');
它不起作用,我无法使用该$client->submitForm()
方法,因为表单是由另一个应用程序发送的。
也许它来自我的 Api 端点,因为我使用的是 $_POST 变量?:
$res = false;
if(count($_POST) === 2){
$user = $this->userrepo->findByName($_POST['value1']);
if($user){
if($this->passwordEncoder->isPasswordValid($user[0], $_POST['value2'])){
$res = true;
}
}
}
return new Response($this->serializer->serialize(['isChecked' => $res], 'json'));
我的测试方法从未通过第一个 if 语句,这里是我的测试方法:
$client = static::createClient();
$client->request('POST', '/url', ['value1' => 'value1', 'value2' => 'value2']);
$this->assertStringContainsString('{"isChecked":true}', $client->getResponse()->getContent());
这是我要发送的 POST 请求:
curl --location --request POST 'http://localhost:8000/url' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--form 'value1=value1' \
--form 'value2=value2'
解决方案
Symfony 的测试客户端在内部分派请求。全局$_POST
变量将始终为空。您应该使用Request
控制器中的对象来访问参数。该属性request
包含发布数据。
public function myAction(Request $request): Response
{
$postParameters = $request->request;
$res = false;
if ($postParameters->count() === 2) {
$user = $this->userrepo->findByName($postParameters->get('value1'));
if ($user) {
if ($this->passwordEncoder->isPasswordValid($user[0], $postParameters->get('value2'))) {
$res = true;
}
}
}
return new Response($this->serializer->serialize(['isChecked' => $res], 'json'));
}
关于您的测试调用的不同变体,这应该与上述操作一起使用。
$client->request('POST', '/url', ['value1' => 'value1', 'value2' => 'value2']);
推荐阅读
- java - 使用不信任服务器自签名证书导致“未找到证书路径的信任锚”
- linkedin - LinkedIn 共享 URL 未填充消息/标题
- xpages - xp:inputtext 的验证会冻结我的 Xpage,为什么?
- azure - 如何将数据文件从客户端 Azure Blob 复制到本地 Blob 存储?
- reactjs - 应用 value 道具而不重新渲染
- java - 正则表达式允许带有 numberDecimal 的 $ 符号
- php - 没有绑定参数的 Mysqli 准备好的语句
- java - 我如何在没有应用引擎的情况下连接谷歌云实例
- php - 如何在 ejabbred 中使用 api 获取用户头像?
- image - Docker Pull 命令与 Docker Build 命令有何不同