Laravel 单元测试 json 响应

Laravel unit testing json response

我的应用程序中有以下测试。但是响应没有通过测试,我不明白为什么...

public function test_get()
{
    $user = $this->signInAsUser();
    
    $product = factory('App\Models\Product')->create();

    factory('App\Models\Stock')->create([
        'product_id' => $product->id,
        'qty' => $qty = rand(1, 100),
    ]);

    $this->json('GET', '/api/stock', , ['Accept' => 'application/json'])
        ->assertStatus(200)
        ->assertJson([
            'data' => [
                'product_id' => "$product->id",
                'stock' => "$qty"
            ]
        ]);
}

这会从 PHPUnit 生成以下内容:

Unable to find JSON: 

[{
    "data": {
        "product_id": "1",
        "stock": "55"
    }
}]

within response JSON:

[{
    "data": [
        {
            "product_id": "1",
            "stock": "55"
        }
    ]
}].


Failed asserting that an array has the subset Array &0 (
    'data' => Array &1 (
        'product_id' => '1'
        'stock' => '55'
    )
).

断言未通过测试,我不明白为什么 JSON 在我看来是一样的...

您断言您的 JSON 响应是单个对象,而它是一个对象数组。尝试使用 assertJsonFragment 而不是 assertJson.