在 PhpUnit 测试中匹配 JsonStructure - Laravel 5.4

Match JsonStructure in PhpUnit Test - Laravel 5.4

我正在创建单元测试并想测试响应中返回的 JSON 结构。我知道 TestResponse 提供了一种方法 assertJsonStructure 来匹配您的 JSON 响应的结构。但出于某种原因,我无法将 $structure 映射到我的响应,结果测试失败。让我分享所需的片段。

端点响应

{
   "status": true,
   "message": "",
   "data": [
       {
          "id": 2,
          "name": "Shanelle Goodwin",
          "email": "chaz43@example.net",
          "created_at": "2017-03-05 16:12:49",
          "updated_at": "2017-03-05 16:12:49",
          "user_id": 1
       }
    ]
}

测试函数

public function testEndpoint(){

  $response = $this->get('/api/manufacturer/read', [], $this->headers);
  $response->assertStatus(200);
  $response->assertJsonStructure([
    'status',
    'message',
    'data' => [
      {
        'id',
        'name',
        'email',
        'created_at',
        'updated_at',
        'user_id'
      }
    ]
  ]);
  var_dump("'/api/manufacturer/read' => Test Endpoint");
}

data 数组中可以有多个节点,这就是为什么我试图在结构中提及数组但似乎没有映射 correctly.Any 帮助将不胜感激:-)

我认为你应该使用:

 $response->assertJsonStructure([
    'status',
    'message',
    'data' => [
      [ // change here
        'id',
        'name',
        'email',
        'created_at',
        'updated_at',
        'user_id'
      ] // change here
    ]
  ]);

幸运的是,通过尝试不同的选项我已经解决了这个问题。如果我们要匹配数组中的嵌套对象,则应将“*”作为键。我们可以在这里看到引用。

Source: TestResponse

我已经为 array ofobjects`

设置了这样的结构
$response->assertJsonStructure([
    'status',
    'message',
    'data' => [
      '*' => [
        'id',
        'name',
        'email',
        'created_at',
        'updated_at',
        'user_id'
      ]
    ]
  ]);

如果您只想匹配一个对象

$response->assertJsonStructure([
    'status',
    'message',
    'data' => [
      [
        'id',
        'name',
        'email',
        'created_at',
        'updated_at',
        'user_id'
      ]
    ]
  ]);