Symfony 5.4迁移后PHPUnit API认证测试报Invalid JSON错误求助
问题分析
你遇到的Invalid JSON. (400 Bad Request)错误,核心原因是请求数据格式与声明的Content-Type不匹配:
- 你通过
HTTP_CONTENT_TYPE设置请求为application/json,但调用client->request()时直接传入PHP数组作为请求体,Symfony测试Client默认会把数组编码为application/x-www-form-urlencoded格式,而非JSON,导致后端解析JSON失败。
修复方案
修改authUser方法里的request调用逻辑,将参数数组转为JSON字符串,并按Client::request()的参数规范传递:
public function authUser($username='stack.fr', $password='overflow', $referer='https://stack.over.local/') { $this->newClient(); $this->client->request( 'POST', '/api/login_check', [], // URL参数占位(无则留空) [], // 文件上传参数占位(无则留空) [ 'CONTENT_TYPE' => 'application/json', 'HTTP_REFERER' => $referer, 'HTTPS' => true, 'HTTP_HOST' => $this->client->getContainer()->getParameter('api_host') ], json_encode([ '_username' => $username, '_password' => $password, ]) ); $responseContent = $this->client->getResponse()->getContent(); $response = json_decode($responseContent, true); if (isset($response['token'])) { $this->client->setServerParameter('HTTP_AUTHORIZATION', 'Bearer ' . $response['token']); } return $response; }
额外优化点
修正容器调用逻辑:
原代码中self::$container->getParameter('api_host')存在初始化顺序风险,改为从当前客户端实例获取容器更可靠:$this->client->getContainer()->getParameter('api_host')统一Content-Type参数名:
Symfony中标准的请求内容类型参数是CONTENT_TYPE(不带HTTP前缀),替换原代码中的HTTP_CONTENT_TYPE,避免兼容性问题。增加响应校验:
可以在解码前先验证响应类型,避免非JSON内容导致的解码错误:if ($this->client->getResponse()->headers->get('Content-Type') !== 'application/json') { throw new \RuntimeException('认证接口未返回JSON格式响应'); }
内容的提问来源于stack exchange,提问作者oracle972
相关产品推荐
相关产品推荐

