Reputation: 185
I want to test my restful controller consuming json data. The problem is that I am unable to send the data correctly.
This is how I try to send the data:
$this->configRequest([
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
]);
$this->post('/api/users', "{'username':'Iason','password':'test'}");
debug($this->_response->body());
In my controller, I check the data:
if (empty($this->request->data)) {
throw new BadRequestException("No data");
}
The check fails and I get back the error.
If I test my API using Postman, everything works fine. If I try to send the data as an array (which is shown in the manual http://book.cakephp.org/3.0/en/development/testing.html#controller-integration-testing), I don't have any request data in controller either. I have no idea what I'm doing wrong.
Upvotes: 1
Views: 821
Reputation: 60493
First of all that's invalid JSON data, strings must be enclosed in double quotes ("
), not single quotes ('
).
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes.
The other problem is that non-form post data, ie non application/x-www-form-urlencoded
formatted POST body data has to be set via the input
option:
$this->configRequest([
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
'input' => '{"username":"Iason","password":"test"}'
]);
$this->post('/api/users');
Wouldn't hurt if the docs had an example showing that.
Upvotes: 4