Laravel 8中如何在AssertableJson中测试JSON响应的数组长度?
方法1:使用has方法直接验证数组长度(推荐)
Laravel的AssertableJson提供的has方法支持第二个参数传入数字,直接验证对应键的数组长度,该方法会自动验证键存在、对应值为数组、且数组长度匹配你传入的数值,不需要额外写whereType判断:
$response ->assertSuccessful() ->assertJson(function (AssertableJson $json) use ($allElementsCount) { // 适配你的分页逻辑:总数据≥10则返回10条,否则返回全部 $expectedLength = $allElementsCount >= 10 ? 10 : $allElementsCount; $json ->has('data', $expectedLength) // 直接验证data数组长度 ->etc(); });
如果需要同时验证data数组内每个元素的结构,可以在长度参数后再传入闭包:
->has('data', 10, function (AssertableJson $item) { $item->hasAll(['id', 'title', 'created_at']); // 验证单条数据的字段结构 })
方法2:使用自定义闭包实现灵活判断
如果你的长度判断逻辑更复杂(比如只需验证长度不超过10),可以用where方法传入自定义闭包处理:
$response ->assertSuccessful() ->assertJson(function (AssertableJson $json) { $json ->has('data') ->whereType('data', 'array') ->where('data', fn (array $data) => count($data) <= 10) // 自定义长度判断规则 ->etc(); });
内容的提问来源于stack exchange,提问作者netdjw
相关产品推荐
相关产品推荐

