首页 > 解决方案 > Laravel API Illuminate\Foundation\Testing\TestResponse 空数组时期望单个对象

问题描述

为什么从 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 中看到它”。

标签: laravellaravel-5guzzle

解决方案


来自有关响应的 laravel 文档:

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

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

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

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


推荐阅读