英文:
How can I assert array with object in Laravel?
问题
我想要断言数组伪造数据与对象。我使用 assertEquals()
,但它不起作用。如何断言这些属性?
$fakeData = [
'id' => 1,
'first_name' => fake()->firstName,
'last_name' => fake()->lastName,
'city' => fake()->city,
];
$myquery = DB::table('users')
->select('id', 'first_name', 'last_name', 'city')
->where('id', '=', 1)
->get();
$this->assertEquals($fakeData, $myquery);
英文:
I want to assert array fake data with object. I use assertEquals()
but it is not working. How can I assert the properties?
$fakeData = [
'id' => 1,
'first_name' => fake()->firstName,
'last_name' => fake()->lastName,
'city' => fake()->city,
];
$myquery = DB::table('users')
->select('id', 'first_name', 'last_name', 'city')
->where('id', '=', 1)
->get();
$this->assertEquals($fakeData, $myquery);
答案1
得分: 1
Laravel
中的DB,以您当前的使用方式,返回一个集合。首先让它返回一个对象。因此,您的虚假数据也应该是一个对象,PHP
可以使用强制类型转换(array)
或(object)
轻松地在数组和对象之间进行转换。
$fakeData = (object)[
'id' => 1,
'first_name' => fake()->firstName,
'last_name' => fake()->lastName,
'city' => fake()->city,
];
$myRow = DB::table('users')
->select('id', 'first_name', 'last_name', 'city')
->where('id', '=', 1)
->first();
$this->assertEquals($fakeData, $myRow);
更实际的情况是,大多数情况下,使用assertDatabaseHas()
更容易断言数据库中的内容。
$this->assertDatabaseHas(
'users',
[
'id' => 1,
'first_name' => 'some_first_name',
'last_name' => 'some_last_name',
'city' => 'some_city',
]
);
英文:
Laravel's
DB in the way you are using it, returns an collection. Firstly get it to return an object instead. Therefor your fake data should also be an object, PHP
can easily convert arrays to objects and vice versa with casting (array)
or (object)
.
$fakeData = (object)[
'id' => 1,
'first_name' => fake()->firstName,
'last_name' => fake()->lastName,
'city' => fake()->city,
];
$myRow = DB::table('users')
->select('id', 'first_name', 'last_name', 'city')
->where('id', '=', 1)
->first();
$this->assertEquals($fakeData, $myRow);
In more practical terms, most of the times it is easier to assert what is in the database, using assertDatabaseHas()
instead.
$this->assertDatabaseHas(
'users',
[
'id' => 1,
'first_name' => 'some_first_name',
'last_name' => 'some_last_name',
'city' => 'some_city',
],
);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论