phpunit 和 http content-type

phpunit and http content-type

我在 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());
    }

}

同时我的 API 端点指向这个控制器函数

private function store()
{

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

    // the code continues
    ...
}

然而它总是失败,因为API无法识别负载。 Input::getContent() returns JSON 但 Input::only() returns 空白。进一步调查这是因为如果请求负载的内容类型为 JSON

,则 Input::only() 仅 returns 值

那么...如何设置上面的 phpunit 代码以使用 content-type application/json ?我假设它一定与 $server 有关,但我不知道

编辑: 我原来的想法其实有2个问题

  1. Input::getContent() 有效,因为我填写了第六个参数,但 Input::only() 无效,因为我没有填写第三个参数。感谢@shaddy
  2. 如何在 phpunit 请求中设置 content-type header 仍然没有答案

多谢

调用函数的第三个参数必须是您作为输入参数发送到控制器的参数——在您的例子中是数据参数。

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

像下面的例子那样改变你的代码应该可行(你不必 json_encode 数组):

$this->response = $this->call('POST', '/products', $data);

在Laravel 5.4及更高版本中,您可以像Content-Type一样验证headers的响应(docs):

$this->response->assertHeader('content-type', 'application/json');

或 Laravel 5.3 及以下 (docs):

$this->assertEquals('application/json', $response->headers->get('Content-Type'));