laravel - 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 中看到它”。
解决方案
来自有关响应的 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
推荐阅读
- c - 如何使用 Arduino 在 LCD 上无延迟()方法闪烁单个字符?
- php - (PHP) 为什么这是以下回显的输出?
- c# - 缺少 MSBuildCommunityTasks 文件夹
- dataprovider - 在 Genexus 中将 SDT 数据转换为 BC
- c++ - #define 一个宏和模板,它将运行任何类型的函数,包括 void,并返回平均运行时间?
- c++ - 我是否需要在头文件和源文件中指定调用约定
- spring-kafka - 从 Spring Boot 应用程序调用 ConsumConsumerSeekCallback 的 seek
- python - json 文件在使用 python 放入 zip 存档时损坏
- swift - CBCentralManager 状态最初注册为 .unknown
- arrays - 对数组中的奇数进行排序,同时保持偶数不变