我想编写一个测试来创建一个用户,然后使用该路由测试该用户是否显示在Users API索引集合中。
我已经阅读了documentation,并使用Laravel和PHPUnit编写了REST API测试。我很难通过assertJson
,因为它返回以下错误:
Failed asserting that an array has the subset Array &0 (
'name' => 'Buck Trantow V'
'email' => 'marianne.leffler@example.org'
'username' => 'hhudson'
).
--- Expected
+++ Actual
@@ @@
array (
),
),
- 'name' => 'Buck Trantow V',
- 'email' => 'marianne.leffler@example.org',
- 'username' => 'hhudson',
)
测试:
public function testUserIndex()
{
$user = factory(User::class)->create();
$response = $this
->actingAs($user, 'api')
->json('GET', '/api/users')
->assertStatus(200);
$response
->assertJson([
'name' => $user->name,
'email' => $user->email,
'username' => $user->username,
]);
}
路由/用户控制器:
Route::resource('users', 'UserController');
UserController:
public function index()
{
return User::all();
}
答案 0 :(得分:1)
将其发布给需要它的任何人。.我发现assertJsonFragment
适用于这种情况。
$response
->assertJsonFragment([
'name' => $user->name,
'email' => $user->email,
'username' => $user->username,
]);