首页 > 解决方案 > 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'

标签: phpsymfonyphpunit

解决方案


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']);

推荐阅读