【问题标题】:CakePHP3 integration test and json dataCakePHP3 集成测试和json数据
【发布时间】:2015-02-05 03:50:00
【问题描述】:

我想测试使用 json 数据的 restful 控制器。问题是我无法正确发送数据。

这就是我尝试发送数据的方式:

$this->configRequest([
    'headers' => [
        'Accept' => 'application/json',
        'Content-Type' => 'application/json'
    ],
]);

$this->post('/api/users', "{'username':'Iason','password':'test'}");

debug($this->_response->body());

在我的控制器中,我检查数据:

if (empty($this->request->data)) {
    throw new BadRequestException("No data");
}

检查失败,我得到了错误。

如果我使用 Postman 测试我的 API,一切正常。如果我尝试将数据作为数组发送(如手册 http://book.cakephp.org/3.0/en/development/testing.html#controller-integration-testing 中所示),控制器中也没有任何请求数据。 我不知道我做错了什么。

【问题讨论】:

    标签: json cakephp testing integration cakephp-3.0


    【解决方案1】:

    首先是无效的 JSON 数据,字符串必须用双引号 (") 括起来,而不是单引号 (')。

    值可以是双引号中的字符串、数字、true 或 false 或 null,也可以是对象或数组。这些结构可以嵌套。

    字符串是零个或多个 Unicode 字符的序列,用双引号括起来,使用反斜杠转义。

    http://www.json.org/

    另一个问题是非表单的post数据,即非application/x-www-form-urlencoded格式的POST正文数据必须通过input选项设置:

    $this->configRequest([
        'headers' => [
            'Accept' => 'application/json',
            'Content-Type' => 'application/json'
        ],
        'input' => '{"username":"Iason","password":"test"}'
    ]);
    
    $this->post('/api/users');
    

    如果文档有一个例子表明这一点,不会有什么坏处。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-17
      • 1970-01-01
      • 2010-09-08
      • 1970-01-01
      • 2018-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多