在Laravel中如何断言带有对象的数组?

huangapple go评论70阅读模式
英文:

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',
    ],
);

huangapple
  • 本文由 发表于 2023年3月9日 18:43:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75683499.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定