You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 03:48:00