Tuesday, March 7, 2017

Match JsonStructure in PhpUnit Test - Laravel 5.4

I am creating a unit test and want to test the JSON structure returned in the response. I am aware that the TestResponse provides a method assertJsonStructure to match the structure of your JSON response. But for some reason I am unable to map the $structure to my response and in result the test fails. Let me share the required snippets.

Endpoint Response

{
   "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
       }
    ]
}

Test Function

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");
}

There can multiple nodes in data array so that is why i tried to mention the array in structure but seems it doesn't map correctly.Any help would be appreciated :-)



via Farooq Khan

Advertisement