You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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;
}
额外优化点
  1. 修正容器调用逻辑:
    原代码中self::$container->getParameter('api_host')存在初始化顺序风险,改为从当前客户端实例获取容器更可靠:

    $this->client->getContainer()->getParameter('api_host')
    
  2. 统一Content-Type参数名:
    Symfony中标准的请求内容类型参数是CONTENT_TYPE(不带HTTP前缀),替换原代码中的HTTP_CONTENT_TYPE,避免兼容性问题。

  3. 增加响应校验:
    可以在解码前先验证响应类型,避免非JSON内容导致的解码错误:

    if ($this->client->getResponse()->headers->get('Content-Type') !== 'application/json') {
        throw new \RuntimeException('认证接口未返回JSON格式响应');
    }
    

内容的提问来源于stack exchange,提问作者oracle972

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 05:15:38