【问题标题】:phpunit and http content-typephpunit 和 http 内容类型
【发布时间】:2015-08-26 15:24:24
【问题描述】:

我在 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() 返回 JSON,但 Input::only() 返回空白。进一步调查这是因为 Input::only() 仅在请求有效负载的内容类型为 JSON 时才返回值

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

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

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

谢谢大家

【问题讨论】:

    标签: rest laravel phpunit dingo-api


    【解决方案1】:

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

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

    像下面的例子一样改变你的代码应该可以工作(你不必对数组进行 json_encode):

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

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

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

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

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

    【讨论】:

    • 感谢您让 phpunit 测试正常工作。但是,最初的问题是,如何在 phpunit 测试用例中设置内容类型?还是我不需要担心内容类型?
    • @DonDjoe 我已经更新了我的答案,举例说明如何验证响应内容类型。
    • 谢谢@shaddy,我该如何设置请求的内容类型呢?不验证
    • @DonDjoe 你可以在你的控制器中这样做return response($content, $status)->header('Content-Type', $value);
    • @DonDjoe 在请求中,您可以像这样将其作为服务器参数传递$this->response = $this->call('POST', '/products', $data, [], [], ['CONTENT_TYPE' => 'application/json']);
    猜你喜欢
    • 1970-01-01
    • 2020-01-01
    • 2017-01-24
    • 2015-11-18
    • 2012-12-29
    • 2012-04-07
    • 2016-07-27
    • 2016-04-17
    • 1970-01-01
    相关资源
    最近更新 更多