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

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

$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数据,字符串必须用双引号(")而不是单引号(')括起来。


  值可以是带双引号的字符串,也可以是数字,也可以是true或false或null,或者是对象或数组。这些结构可以嵌套。
  
  字符串是零个或多个Unicode字符的序列,使用反斜杠转义符将其括在双引号中。


http://www.json.org/

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

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

$this->post('/api/users');


如果文档中有显示该示例的示例,则不会造成伤害。

08-04 10:25
查看更多