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

Codeception测试WPGraphQL时布尔true被转为字符串"1"的原因是什么?

问题诱因
  • Codeception REST模块默认POST请求采用application/x-www-form-urlencoded编码格式,该格式不支持原生布尔类型,会自动将PHP布尔值true转换为字符串"1"、false转换为空字符串,最终传到WPGraphQL解析时不符合Schema定义的Boolean类型要求。
  • 生产环境请求无报错是因为正常业务请求发送GraphQL时统一使用application/json格式编码,JSON格式可以原生保留布尔、数值等数据类型,不会出现强制类型转换的问题。
  • 测试代码的写法触发了默认编码逻辑:调用$I->send()方法时直接传入数组作为请求体参数,REST模块会默认走表单编码流程,不会将参数序列化为JSON,最终导致布尔值被转义。
修复方案

直接使用REST模块提供的sendPostAsJson方法替代原send方法,该方法会自动设置Content-Type: application/json请求头,且将请求参数序列化为JSON格式保留原有数据类型:

class RegisterCest { 

   public function seeCanRegister( ApiTester $I ) {
      // 替换send为sendPostAsJson即可
      $I->sendPostAsJson( "https://example.com/graphql", [
         "query" => '
            mutation registerUser( $input: RegisterUserInput! ) {
               registerUser( input: $input ) {
                  user {
                     username
                     email
                     addressMain
                     addressSec
                     adminArea
                     country
                     city
                     firstName
                     lastName
                     postalCode
                  }
               }
            }         
         ',
         "variables" => [
            "input" => [
               "clientMutationId" => "registerUser",
               "firstName" => "John",
               "lastName" => "Smith",
               "username" => "user@example.com",
               "email" => "user@example.com",
               "password" => "example",
               "addressMain" => "Fake Street",
               "addressSec" => "Apt #1",
               "adminArea" => "New York",
               "country" => "US",
               "city" => "New York",
               "postalCode" => 00000,
               "planSlug" => null,
               "subscribeToNewsletter" => true
            ]
         ]
      ]);

      $I->seeResponseCodeIs( 200 );
      $I->dontSeeResponseJsonMatchesJsonPath( "$.errors" );   

   }

}

也可以手动指定请求头并序列化参数:

$I->haveHttpHeader('Content-Type', 'application/json');
$I->send("POST", "https://example.com/graphql", json_encode($请求参数数组));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 10:06:05