Laravel 5.6。如何测试 JSON/JSONb 列

Laravel 5.6. How to test JSON/JSONb columns

$this->assertDatabaseHas() 不适用于 JSON/JSONb 列。

那么如何在 Laravel 中测试这些类型的列?

目前,我有一个商店动作。我如何执行断言,即保存了具有预定义值的特定列。

类似

['options->language', 'en']

不是一个选项,因为我有大量JSON元数据。

如何一次性查看数据库中的JSON

UPD

现在可以完成了like that.


我已经用这个单行解决了(根据你的models/fields调整)

$this->assertEquals($store->settings, Store::find($store->id)->settings);

Laravel 7+

不确定该解决方案在多长时间前有效。

我找到了解决办法。忽略一些数据标签,一切都是可访问的,我只是在玩我的测试来弄清楚。

/**
 * @test
 */
public function canUpdate()
{
    $authUser = UserFactory::createDefault();
    $this->actingAs($authUser);

    $generator = GeneratorFactory::createDefault();

    $request = [
        'json_field_one' => [
            'array-data',
            ['more-data' => 'cool'],
            'data' => 'some-data',
            'collection' => [
                ['key' => 'value'],
                'data' => 'some-more-data'
            ],
        ],
        'json_field_two' => [],
    ];

    $response = $this->putJson("/api/generators/{$generator->id}", $request);
    $response->assertOk();

    $this->assertDatabaseHas('generators', [
        'id' => $generator->id,
        'generator_set_id' => $generator->generatorSet->id,

        // Testing for json requires arrows for accessing the data
        // For Collection data, you should use numbers to access the indexes
        // Note:  Mysql dose not guarantee array order if i recall. Dont quote me on that but i'm pretty sure i read that somewhere.  But for testing this works
        'json_field_one->0' => 'array-data',
        'json_field_one->1->more-data' => 'cool',

        // to access properties just arrow over to the property name
        'json_field_one->data' => 'some-data',
        'json_field_one->collection->data' => 'some-more-data',

        // Nested Collection
        'json_field_one->collection->0->key' => 'value',

        // Janky way to test for empty array
        // Not really testing for empty
        // only that the 0 index is not set
        'json_field_two->0' => null,
    ]);
}

在对我有用的值上使用 json_encode

$this->assertDatabaseHas('users', [
    'name' => 'Gaurav',
    'attributes' => json_encode([
        'gender' => 'Male',
        'nationality' => 'Indian',
    ]),
]);

Note: The below solution is tested on Laravel Version: 9.x and Postgres version: 12.x and the solution might not work on lower version of laravel

将 json 列断言到数据库中有两个条件。

1。对象

考虑对象位于数据库的 json 列中,如下所示:

 "properties" => "{"attributes":{"id":1}}"

它可以断言为

$this->assertDatabaseHas("table_name",[
    "properties->attributes->id"=>1
]);

2。数组

考虑数组在 json 列中,如下所示:

 "properties" => "[{"id":1},{"id":2}]"

它可以断言为

$this->assertDatabaseHas("table_name",[
    "properties->0->id"=>1,
    "properties->1->id"=>2,
]);