phpunit和http内容类型

Don*_*joe 3 rest phpunit laravel dingo-api

我有一个用Laravel(Dingo)构建的API,它运行得很好.但是我在实现phpunit来测试我的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());
    }

}
Run Code Online (Sandbox Code Playgroud)

同时我的API端点指向此控制器功能

private function store()
{

    // This always returns null
    $shortInput = Input::only("price");
    $rules = [
            "price" => ["required"]
    ];
    $validator = Validator::make($shortInput, $rules);

    // the code continues
    ...
}
Run Code Online (Sandbox Code Playgroud)

但是它总是失败,因为API无法识别有效负载.Input :: getContent()返回JSON,但Input :: only()返回空白.进一步调查这是因为如果请求有效负载的内容类型是JSON,则Input :: only()仅返回值

那么......如何设置上面的phpunit代码以使用内容类型的application/json?我假设它必须与之有关$server但我不知道是什么

编辑:我原来的想法实际上有两个问题

  1. Input :: getContent()有效,因为我填充了第六个参数但是Input :: only()不起作用,因为我没有填充第三个参数.感谢@shaddy
  2. 如何在phpunit请求标头中设置内容类型仍然没有答案

谢谢堆

sha*_*ddy 9

调用函数的第三个参数必须是您作为输入参数发送到控制器的参数 - 在您的情况下是数据参数.

$ response = $ this-> call($ method,$ uri,$ parameters,$ cookies,$ files,$ server,$ content);

像下面的例子一样更改你的代码应该有效(你不必对数组进行json_encode):

$this->response = $this->call('POST', '/products', $data);
Run Code Online (Sandbox Code Playgroud)

在Laravel 5.4及更高版本中,您可以验证标题的响应,如内容类型,如此(docs):

$this->response->assertHeader('content-type', 'application/json');
Run Code Online (Sandbox Code Playgroud)

或者对于Laravel 5.3及以下版本(docs):

$this->assertEquals('application/json', $response->headers->get('Content-Type'));
Run Code Online (Sandbox Code Playgroud)

  • @DonDjoe在请求中,您可以将其作为服务器参数传递,例如`$ this-> response = $ this-> call('POST','/ products',$ data,[],[],['CONTENT_TYPE'= >'application/json']);` (2认同)