首页 > 解决方案 > Laravel:在列中使用布尔值创建的工厂无法通过 mysql 数据库中的 assertDatabaseHas 测试用例

问题描述

问题

我有我的表示例,其中列has_value和 has_condition 是 laravel 在 MySQL 中创建的布尔类型。在样本表的工厂中,我将 faker 值设置为布尔值。在测试用例中,我已经通过了 faker 值。laravel 正确存储了值,但是带有 assertDatabaseHas 的测试用例失败,因为 MySQL 将值存储在数值中,但伪造者提供了布尔值。

设置

移民

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

标签: phpmysqllaravelphpunit

解决方案


推荐阅读