laravel - 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();
}
解决方案
在这里为任何需要它的人发帖。我发现这assertJsonFragment
适用于这种情况。
$response
->assertJsonFragment([
'name' => $user->name,
'email' => $user->email,
'username' => $user->username,
]);
推荐阅读
- javascript - 如何通过 react.js 组件中的表格显示 json 数据
- node.js - Bcrypt 密码比较不起作用。在 Node.js Express App 中,甚至 user.password 都是空的
- dart - 是否可以修改 Dart 中参数的引用?
- javascript - 混淆两个正则表达式以检查至少一个数字
- javascript - 如何在另一个选择列表的更改功能上更改选择列表的值?
- android - 将 Google Cameraview 添加到项目中
- flutter - 动画在颤动中很慢
- java - 搜索我所有的数据库表 - MySQL、JAVA
- angular - Angular 7登录后如何携带令牌并访问其他页面?- JWT 认证示例
- javascript - 如何打破承诺的链条