Laravel:在列中使用布尔值创建的工厂无法通过mysql数据库中assertDatabaseHas的测试用例

l2osamch  于 2023-05-30  发布在  Mysql
关注(0)|答案(1)|浏览(197)

问题

我有一个表sample,其中的列has_value和has_condition是由MySQL中的laravel创建的布尔类型。在sample表的Factory中,我将faker值设置为boolean。在测试用例中,我已经传递了faker值。laravel正确地存储了值,但是assertDatabaseHas的测试用例失败了,因为MySQL以数字值存储值,但是faker提供了布尔值。

设置

迁移

Schema::create('sample', function (Blueprint $table) {
   $table->unsignedBigInteger();
   $table->boolean('has_value')->default(false);
   $table->boolean('has_condition')->default(false);
});

型号

class Sample extends Model {
  
   /**
     * The attributes that aren't mass assignable.
     *
     * @var array
     */
    protected $guarded = ['id', 'created_at', 'updated_at'];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'has_condition' => 'boolean',
        'has_value' => 'boolean',
    ];
}

工厂

$factory->define(Sample::class, function (Faker $faker) {
    return [
        'has_condition' => $faker->boolean,
        'has_value' => $faker->boolean
    ];
});

测试用例

use DatabaseMigrations;

public function test_is_being_stored()
{
  $data = factory(Sample::class)->make()->toArray();
  $user = factory(User::class)->create()
  $this->actingAs($user)->post(route('some.route.store'), $data)
    ->assertSessionHasNoErrors()
    ->assertStatus(200);

  $this->assertDatabaseHas('sample', $data)
}

结果如下

Failed asserting that a row in the table [campaign_tax_years] matches the attributes {
    "has_condition": true,
    "has_value": true
}.

Found: [
    {
        "id": 27,
        "created_at": "2020-07-01 07:36:52",
        "updated_at": "2020-07-01 07:36:52",
        "has_condition": 1,
        "has_value": 1
    }
]

数据库中的值检查不是类型转换检查。但是存储的值是正确的。我无法理解为什么Laravel不转换值,然后检查列类型。

各种项目版本

Laravel:6.8.x Mysql:5.7.29 Phpunit:^8.0

ogsagwnx

ogsagwnx1#

你可以在TestCase类中编写一个方法,如下所示:

protected function convertBooleansToInteger($attributes)
{
    return array_map(fn($v) => $v === false ? 0 : ($v === true ? 1 : $v), $attributes);
}

然后我们:

public function test_is_being_stored()
{
  $data = factory(Sample::class)->make()->toArray();
  $user = factory(User::class)->create()
  $this->actingAs($user)->post(route('some.route.store'), $data)
    ->assertSessionHasNoErrors()
    ->assertStatus(200);

  $data = $this->convertBooleansToInteger($data)

  $this->assertDatabaseHas('sample', $data)
}

相关问题