Phpunit and http content-type
I have an API built in Laravel (Dingo) and it works great. However, I have a problem with phpunit implementation to unit test my API
class ProductControllerTest extends TestCase
{
public function testInsertProductCase()
{
$data = array(
, "description" => "Expensive Pen"
, "price" => 100
);
$server = array();
$this->be($this->apiUser);
$this->response = $this->call('POST', '/products', [], [], $server, json_encode($data));
$this->assertTrue($this->response->isOk());
$this->assertJson($this->response->getContent());
}
}
Meanwhile my API endpoint points to this controller function
private function store()
{
// This always returns null
$shortInput = Input::only("price");
$rules = [
"price" => ["required"]
];
$validator = Validator::make($shortInput, $rules);
// the code continues
...
}
However, it always fails as the API cannot recognize the payload. Input :: getContent () returns JSON, but Input :: only () returns empty. Further exploration is that Input :: only () only returns a value if the content type of the request payload is in JSON
So ... how can I set my phpunit code above to use content type / json app? I'm guessing it must have something to do with $server
, but I don't know what
Edit: There are actually 2 problems with my original thinking
- Input :: getContent () works because I fill in the sixth parameter, but Input :: only () doesn't work because I didn't fill in the third parameter. Thanks @shaddy
- How to set content type in request header phpunit is still unanswered.
Thanks heaps
source to share
The third parameter of the call function should be parameters that you send to the controller as input parameters - in your case the data parameter.
$ response = $ this-> call ($ method, $ uri, $ parameters, $ cookies, $ files, $ server, $ content);
Changing code like the example below should work (you don't need the json_encode of the array):
$this->response = $this->call('POST', '/products', $data);
You can check the content type of the response like this:
$this->assertEquals('application/json', $response->headers->get('Content-Type'));
I suggest you read the documentation carefully.
source to share