【问题标题】:Laravel unit testing json responseLaravel 单元测试 json 响应
【发布时间】:2022-01-20 08:09:08
【问题描述】:

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

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 对我来说看起来一样...

【问题讨论】:

  • 响应是一个对象数组(见{}),你的请求发送一个字符串数组

标签: php laravel phpunit


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    相关资源
    最近更新 更多