首页 > 解决方案 > Laravel 使用 assertJson 测试集合 JSON 响应

问题描述

我想编写一个测试来创建一个用户,然后测试用户是否使用该路由显示在用户 API 索引集合中。

我已经阅读了有关使用 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');

用户控制器:

public function index()
    {
        return User::all();
    }

标签: laravelrestlaravel-5phpunitlaravel-5.7

解决方案


在这里为任何需要它的人发帖。我发现这assertJsonFragment适用于这种情况。

      $response
            ->assertJsonFragment([
                'name'     => $user->name,
                'email'    => $user->email,
                'username' => $user->username,
            ]);

推荐阅读