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

如何测试JSON API?Laravel接口测试user_id断言失败求助

Laravel测试报错:Failed asserting that an array has the key 'user_id'

我编写了一个测试交易展示功能的测试用例,但测试失败,报错信息为Failed asserting that an array has the key 'user_id'.,不清楚报错原因。测试代码如下:

public function a_test_display_deals()
{
    $user = User::factory()->create();

    $response = $this->postJson(route('deals.index'), [
        'user_id'         => 1,
        'contract_number' => 26308,
        'amount' => 2681.00
    ]);
    $response->assertJsonStructure([
                'user_id',
                'contract_number',
                'amount'
    ]);

}

可能的原因及解决办法:

  • 路由HTTP方法不匹配:deals.index作为资源路由默认对应GET请求,但你用了postJson()发送POST请求。如果是展示交易列表/详情的接口,应该用GET请求,把postJson改成getJson即可。

  • 硬编码user_id无效:你通过工厂创建了$user,但请求里硬写user_id => 1,如果工厂生成的用户ID不是1(比如数据库已有其他数据),这个参数可能不合法,导致接口返回结构不符合预期。改成'user_id' => $user->id,确保使用刚创建的有效用户ID。

  • 接口返回结构有嵌套层级:很多Laravel接口会把数据包裹在data字段里(比如{"data": {"user_id": 1, ...}}),这时候直接断言顶层的user_id就会失败。可以先打印响应查看真实结构:

    dd($response->json()); // 在断言前添加这行,查看返回的JSON内容
    

    如果确认有data层,调整断言:

    $response->assertJsonStructure([
        'data' => [
            'user_id',
            'contract_number',
            'amount'
        ]
    ]);
    
  • 接口返回的是交易列表:如果deals.index是返回多条交易的列表,返回结构会是数组形式(比如{"data": [{"user_id": 1, ...}]}),这时候断言要对应数组结构:

    $response->assertJsonStructure([
        'data' => [
            '*' => [
                'user_id',
                'contract_number',
                'amount'
            ]
        ]
    ]);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 21:15:41