【发布时间】: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 中看到它”。
【问题讨论】: