PHPUnit和HTTP Content-Type

4

我有一个使用Laravel(Dingo)构建的API,它运行得很完美。然而,我在实现phpunit进行单元测试时遇到了问题。

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()返回JSON,但Input :: only()返回空白。进一步调查发现,这是因为如果请求有效载荷的内容类型为JSON,则Input :: only()仅返回值。
那么...我如何设置我的phpunit代码以使用content-type application / json?我假设它必须与$server有关,但我不知道是什么。
编辑: 实际上,我的原始想法有两个问题:
1. Input :: getContent()有效,因为我填充了第六个参数,但Input :: only()无效,因为我没有填充第三个参数。感谢@shaddy
2.如何在phpunit请求标头中设置内容类型仍未得到答案。
非常感谢。
1个回答

11

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

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

将您的代码更改为以下示例应该可以工作(您不必对数组进行json编码):

$this->response = $this->call('POST', '/products', $data);
在 Laravel 5.4 及以上版本中,您可以像这样验证响应头部的 Content-Type 等内容(请参阅文档):
$this->response->assertHeader('content-type', 'application/json');

或对于 Laravel 5.3 及以下版本(文档):

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

感谢您让phpunit测试正常工作。然而,最初的问题是,在phpunit测试用例中如何设置内容类型?或者我不需要担心内容类型吗? - Don Djoe
@DonDjoe 我已经更新了我的答案,并提供了一个示例,说明如何验证响应内容类型。 - Sh1d0w
谢谢@shaddy,但我如何设置请求的内容类型呢?不需要验证。 - Don Djoe
@DonDjoe 在你的控制器中可以这样做:return response($content, $status)->header('Content-Type', $value); - Sh1d0w
再次感谢。但是,我该如何在phpunit测试用例中设置它?不是控制器。 - Don Djoe
2
@DonDjoe 在请求中,你可以将它作为服务器参数传递,像这样 $this->response = $this->call('POST', '/products', $data, [], [], ['CONTENT_TYPE' => 'application/json']); - Sh1d0w

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接