是什么导致assertJson及其变体失败?

时间:2019-09-27 02:54:22

标签: json automated-tests phpunit laravel-5.8

我不确定测试为什么失败。据我了解,assertJson函数将基本上检查数组中的键值对是否在JSON响应中的任何位置。盯着JSON响应,我可以看到它肯定在那里,所以我不确定自己在忽略什么。数据似乎位于另一个数组中,但是据我所读,assertJson应该能够找到数据,而不管其嵌套深度如何。

我尝试了其他建议的变体,例如“ assertJsonFragment”,甚至手动将我的json响应转换为数组,并使用assertArraySubset检查它,这有点... assertJson已经根据文档进行了操作。

测试:

public function testGetExistingGroupMessage(){
            $user = factory(User::class)->create();
            $group = factory(Group::class)->create();
            $group->users()->save($user);
            //Because default factory also makes a new user and group, we're going to make the model instead then overwrite them.
            $message = factory(GroupMessage::class)->make();
            $message->user_id = $user->id;
            $message->group_id = $group->id;
            $group->messages()->save($message);

            $response = $this->actingAs($user,'api')->json('GET','/api/group-messages/'.$group->id);
            $response->assertStatus(200)->assertJson([
                    'user_id' => $user->id,
                    'message' => $message->message,
                    'group_id' => $group->id,
            ]);
    }

输出:

Unable to find JSON:

[{
    "user_id": 206,
    "message": "my_message",
    "group_id": 97
}]

within response JSON:

[[
    {
        "id": 31,
        "user_id": 206,
        "message": "my_message",
        "group_id": 97,
        "filename": null,
        "file": null,
        "file_path": null,
        "image": null,
        "image_path": null,
        "created_at": "2019-09-27 01:53:20",
        "updated_at": "2019-09-27 01:53:20",
        "deleted_at": null,
        "lat": null,
        "lng": null,
        "user": {
            "id": 206,
            "name": "Michaela Shields",
            "email": "muller.cordell@example.org",
            "api_token": null,
            "created_at": "2019-09-27 01:53:20",
            "updated_at": "2019-09-27 01:53:20",
            "deleted_at": null,
            "agent_id": null,
            "device_token": null
        }
    }
]].


Failed asserting that an array has the subset Array &0 (
    'user_id' => 206
    'message' => 'my_message'
    'group_id' => 97
).
--- Expected
+++ Actual
@@ @@
       'device_token' => NULL,
     ),
   ),
-  'user_id' => 206,
-  'message' => 'my_message',
-  'group_id' => 97,
 )

0 个答案:

没有答案