简体   繁体   中英

phpunit and http content-type

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

  1. Input::getContent() works because I fill the sixth parameter but Input::only() doesn't work because i didn't fill the third parameter. Thanks to @shaddy
  2. How to set content-type in phpunit request header is still unanswered

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'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM