2014-12-07 46 views
1

我想测试我的宁静控制器消费JSON数据。问题是我无法正确发送数据。CakePHP3集成测试和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"); 
} 

的检查失败,我回来了错误。

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

回答

3

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

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

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

http://www.json.org/

的另一个问题是,非成形后的数据,即非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'); 

岂不如果文档中有一个例子表明这一点,那么就会受伤。