Laravel API Illuminate\Foundation\Testing\TestResponse 期望单个对象时为空数组
Laravel API Illuminate\Foundation\Testing\TestResponse empty array when expecting single object
为什么在 Laravel 中的单元测试中,如果我执行以下请求,解码 json 响应,它会返回一个空数组:
$response = $this->get(route('api.inspections.get', [
"id" => $inspection->id
]));
$apiInspection = $response->json(); # Empty array :(
然而,对同一个 URL 执行最基本的获取请求却得到了很好的 json 响应。
$inspection = file_get_contents(route('api.inspections.get', [
"id" => $inspection->id
]));
$inspection = json_decode($inspection); # The expected inspection stdClass
谢谢
编辑:我找到了发生这种行为的原因。
从单元测试来看,我使用的 Laravels 隐式路由模型绑定失败了。因此,尽管我认为它应该返回一个 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));
}
所以我在这个简单的任务上浪费了一个小时只是因为我认为 "It clearly works, I can see it in Postman"。
来自 laravel 回复文档:
The json method will automatically set the Content-Type header to
application/json, as well as convert the given array to JSON using the
json_encode PHP function:
return response()->json([
'name' => 'Abigail',
'state' => 'CA' ]);
注意 给定的数组 单词,你给 json() 方法一个空参数,你在 return 中得到它。
您可以在此处查看有关如何测试 json api 的一些示例:https://laravel.com/docs/5.7/http-tests
根据我的编辑,这是隐式路由模型绑定在我的单元测试中不起作用的问题。这是一个已知问题,本身不是 "bug",只是没有很好地记录:
Can't test routes that use model binding (when using WithoutMiddleware trait)
为什么在 Laravel 中的单元测试中,如果我执行以下请求,解码 json 响应,它会返回一个空数组:
$response = $this->get(route('api.inspections.get', [
"id" => $inspection->id
]));
$apiInspection = $response->json(); # Empty array :(
然而,对同一个 URL 执行最基本的获取请求却得到了很好的 json 响应。
$inspection = file_get_contents(route('api.inspections.get', [
"id" => $inspection->id
]));
$inspection = json_decode($inspection); # The expected inspection stdClass
谢谢
编辑:我找到了发生这种行为的原因。 从单元测试来看,我使用的 Laravels 隐式路由模型绑定失败了。因此,尽管我认为它应该返回一个 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));
}
所以我在这个简单的任务上浪费了一个小时只是因为我认为 "It clearly works, I can see it in Postman"。
来自 laravel 回复文档:
The json method will automatically set the Content-Type header to application/json, as well as convert the given array to JSON using the json_encode PHP function:
return response()->json([
'name' => 'Abigail',
'state' => 'CA' ]);
注意 给定的数组 单词,你给 json() 方法一个空参数,你在 return 中得到它。
您可以在此处查看有关如何测试 json api 的一些示例:https://laravel.com/docs/5.7/http-tests
根据我的编辑,这是隐式路由模型绑定在我的单元测试中不起作用的问题。这是一个已知问题,本身不是 "bug",只是没有很好地记录: Can't test routes that use model binding (when using WithoutMiddleware trait)