Laravel/PHPUnit:断言json元素存在但不定义值

Laravel/PHPUnit: Assert json element exists without defining the value

我在测试用例中发送了一个 post 请求,我想断言响应中存在一个特定的元素,假设密钥 'x' 存在。在这种情况下,我不能说 seeJson(['x' => whatever]); 因为我不知道该值。当然,我无法用 seeJson(['x']); 做到这一点。

有办法解决吗?

如果重要: Laravel:v5.2.31 PHPUnit: 5.3.4

虽然它根本不是最优的,但我选择使用这段代码来测试情况:

$this->post(URL, PARAMS)->see('x');

X 是一个假设的名称,实际的元素键在其余数据中出现的可能性很小。否则这个讨厌的解决方法将不切实际。

更新:

正确执行此操作的方法如下:

public function testCaseName()

{
    $this->post(route('route.name'), [
        'param1' => 1,
        'param2' => 10,
    ], [
        'headers_if_any' => 'value'
    ]);

    $res_array = (array)json_decode($this->response->content());

    $this->assertArrayHasKey('x', $res_array);
}

希望对其他人有所帮助。您可以为检查响应编写此测试 json 结构

$this->post('/api/login/', [
        'email' => 'customer3@example.com',
        'password' => '123123123',
    ])->assertJsonStructure([
        'status',
        'result' => [
            'id',
            'email',
            'full_name',
        ],
    ]);