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

Laravel单元测试如何校验JSON响应数组中每个元素的属性值是否正确

错误原因

  • 响应数据层级获取错误:你接口返回的第一层data是分页结构体,包含current_page、data等字段,你当前代码取到的$items是整个分页对象而非条目列表,循环时遍历到分页字段(比如current_page对应值是整型1),尝试读取$item['group_code']就会触发整型值访问数组偏移的报错。
  • 断言方法使用错误:assertJson是用于校验完整响应JSON结构的方法,不能用来直接对比两个字符串是否相等,需要替换为相等断言。

修正后代码

public function test_filter_items_by_group_code_work_properly()
{
    $filterCode = '026';

    $response = $this->get($this->ITEMS_URL . '?' . $this->groupAttribute . '='. $filterCode);

    $response->assertStatus(200);

    // 多取一层data拿到实际条目数组
    $items = $response->json()['data']['data'];
    
    foreach ($items as $item) {
        $item_group = strval($item['group_code']);
        // 替换为相等断言
        self::assertEquals($filterCode, $item_group);
    }
}

内容的提问来源于stack exchange,提问作者Omar Fayad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 07:48:01