I have an API built in Laravel (Dingo) and it works perfectly. However I have a problem with implementing phpunit 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 fail, because the API can't recognise the payload. Input::getContent() returns the JSON but Input::only() returns blank. Further investigation this is because Input::only() only returns value if the content type of the request payload is on JSON
So ... how do I set my phpunit code above to use content-type application/json ? I am assuming it must have something to do with $server
but I don't know what
Edit: There are actually 2 problems with my original thinking
Thanks heaps
The third parameter of the call function must be the parameters 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 your code like the example below should work (you do not have to json_encode the array):
$this->response = $this->call('POST', '/products', $data);
In Laravel 5.4 and above, you can verify the response of headers like the Content-Type like so (docs):
$this->response->assertHeader('content-type', 'application/json');
or for Laravel 5.3 and below (docs):
$this->assertEquals('application/json', $response->headers->get('Content-Type'));