Laravel 测试 assertJsonMissing 不适用于唯一的键。为什么?

问题描述 投票:0回答:2

我正在做一个 tdd 项目,我只是想确保密码不会被错误返回。这是我写的测试。

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

    $response =
        $this
            ->actingAs($user)
            ->get('/api/profile/info');

    $response->assertStatus(200);

    $response->assertJsonStructure(['name', 'fullname', 'email']);

    $response->assertJsonMissing(['password']); // this passes.
    $response->assertJsonMissing(['password' => $user->password]); // this does not pass.
}

我知道密码正在返回,但为什么当我只传递密钥时 assertJsonMissing 不起作用?如果它不用于此,检查数据密钥是否丢失的正确方法是什么?

php laravel testing phpunit tdd
2个回答
1
投票

其实

assertJsonMissing
是测试key,不是value! 你可以为这个问题制定一个特殊的方法或者看看这个: https://laravel.com/docs/10.x/http-tests#assert-json-fragment


1
投票

assertJsonMissing(array $data)
尝试在您返回的 json 中找到
$data

assertJsonMissing(['password'])
assertJsonMissing(['password' => 'something'])
的区别如下:

  • assertJsonMissing(['password'])
    如果返回的 json 是一个对象,则尝试在您的 json 中查找
    {"0": "password"}
  • assertJsonMissing(['password' => 'something'])
    尝试在返回的 json 对象中找到
    {"password": "something"}

这里有几个选择。

  • assertJsonMissingPath('password')
    .
  • 流畅的 json 断言。
$response
    ->assertJson(fn (AssertableJson $json) =>
        $json->hasAll(['name', 'fullname', 'email'])
            ->missing('password')
    );
© www.soinside.com 2019 - 2024. All rights reserved.