【问题标题】:assertJson is not equal to expected to actual in laravelassertJson 不等于 laravel 中预期的实际值
【发布时间】:2022-09-23 18:55:00
【问题描述】:

我是 laravel 单元测试的新手,目前在我的测试中遇到错误。请在下面查看我的代码。

测试

/** @test */
public function users_can_view_homepage_products()
{
    $response = $this->get(\'api/products\');
    
    $response->assertStatus(200)
        ->assertJson([
            \'id\' => 1,
            \'name\' => ucwords($this->faker->words(3, true)),
            \'slug\' => ucfirst($this->faker->slug),
            \'intro\' => $this->faker->sentence,
            \'price\' => number_format($this->faker->randomFloat(2, 100, 99999), 2)
        ]);
}

控制器

public function index()
{
    return [
        \'id\' => 1,
        \'name\' => \'Airpods Pro (2021)\',
        \'slug\' => \'airpods-pro-2021\',
        \'intro\' => \'New and powerful airpods from apple.\',
        \'price\' => 12400
    ];
}

错误

  • 测试用例失败,价格与测试场景不匹配请添加并仅尝试价格中的整数值

标签: laravel unit-testing


【解决方案1】:

测试失败,因为 json 的内容与被测试的内容不同。您可能想测试结构是否相同,而不是内容:

/** @test */
public function users_can_view_homepage_products()
{
    $response = $this->get('api/products');
    
    $response->assertStatus(200)
        ->assertJsonStructure([
            'id',
            'name'
            'slug'
            'intro'
            'price'
        ]);
}

【讨论】:

    猜你喜欢
    • 2016-11-24
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 2020-09-21
    • 2022-01-23
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    相关资源
    最近更新 更多