【问题标题】:Laravel API Illuminate\Foundation\Testing\TestResponse empty array when expecting single object当期望单个对象时,Laravel API Illuminate\Foundation\Testing\TestResponse 空数组
【发布时间】:2019-07-20 13:08:02
【问题描述】:

为什么在 Laravel 的单元测试中,如果我执行以下请求,解码 json 响应,它会以空数组的形式返回:

$response = $this->get(route('api.inspections.get', [
    "id" => $inspection->id
]));

$apiInspection = $response->json(); # Empty array :(

然而,对同一个 URL 执行最基本的 get 请求会得到一个不错的 json 响应。

$inspection = file_get_contents(route('api.inspections.get', [
    "id" => $inspection->id
]));
$inspection = json_decode($inspection); # The expected inspection stdClass

谢谢


编辑:我找到了发生这种行为的原因。 从单元测试中可以看出,我使用的 Laravel 隐式路由模型绑定失败了。所以虽然我认为它应该返回一个 json 对象(因为它来自 Postman),但它实际上返回了 null,因为这可能是 Laravel 中的一个错误。

# So this api controller action works from CURL, Postman etc - but fails from the phpunit tests
public function getOne(InspectionsModel $inspection) {
    return $inspection;
}

所以我不得不把它改成

public function getOne(Request $request) {
    return InspectionsModel::find($request->segment(3));
}

所以我在这个简单的任务上浪费了一个小时,只是因为我认为“它显然有效,我可以在 Postman 中看到它”。

【问题讨论】:

    标签: laravel laravel-5 guzzle


    【解决方案1】:

    来自有关响应的 laravel 文档:

    json 方法会自动将 Content-Type 标头设置为 application/json,以及将给定的数组转换为 JSON 使用 json_encode PHP 函数:

    return response()->json([
        'name' => 'Abigail',
        'state' => 'CA' ]);
    

    注意 given array 词,你给 json() 方法一个空参数,你得到它作为回报。

    您可以在此处查看有关如何测试 json api 的一些示例:https://laravel.com/docs/5.7/http-tests

    【讨论】:

    • 我基本上是在询问当响应是 TestResponse 对象时如何从响应中提取响应主体。它适用于 CURL 请求,但 Laravel 的 http 客户端(可能是 Guzzle?)使它变得复杂。
    【解决方案2】:

    根据我的编辑,这是隐式路由模型绑定在我的单元测试中不起作用的问题。这是一个已知问题,因此不是“错误”,只是没有很好地记录: Can't test routes that use model binding (when using WithoutMiddleware trait)

    【讨论】:

      猜你喜欢
      • 2017-08-24
      • 2020-07-05
      • 2018-10-16
      • 2013-08-12
      • 2015-12-17
      • 2021-10-19
      • 2018-06-20
      • 1970-01-01
      • 2018-06-10
      相关资源
      最近更新 更多