期待单个对象时,Laravel API Illuminate \ Foundation \ Testing \ TestResponse为空数组

问题描述 投票:0回答:2

为什么从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

谢谢


编辑:我发现为什么会发生这种行为。从单元测试看来,Laravels隐式路由模型绑定我使用失败。所以虽然我认为它应该返回一个json对象(因为它是从Postman那里做的)但它实际上是返回null,因为可能是Laravel中的一个bug。

# 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
2个回答
1
投票

来自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的一些示例


0
投票

根据我的编辑,这是隐式路由模型绑定无法从我的单元测试工作的问题。这是一个已知的问题,不是一个“错误”本身,只是没有记录良好:Can't test routes that use model binding (when using WithoutMiddleware trait)

© www.soinside.com 2019 - 2024. All rights reserved.