Max*_*rav 5 php mysql phpunit laravel
我的表示例包含 has_value 和 has_condition 列,它们是由 laravel 在 MySQL 中创建的布尔类型。在示例表的 Factory 中,我将 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);
});
Run Code Online (Sandbox Code Playgroud)
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',
];
}
Run Code Online (Sandbox Code Playgroud)
$factory->define(Sample::class, function (Faker $faker) {
return [
'has_condition' => $faker->boolean,
'has_value' => $faker->boolean
];
});
Run Code Online (Sandbox Code Playgroud)
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)
}
Run Code Online (Sandbox Code Playgroud)
结果如下
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
}
]
Run Code Online (Sandbox Code Playgroud)
数据库中的值检查不是类型转换检查。但存储的值是正确的。我无法理解为什么 Laravel 不转换值然后检查列类型。
Laravel:6.8.x Mysql:5.7.29 Phpunit:^8.0
小智 0
TestCase
您可以在类中编写这样的方法:
protected function convertBooleansToInteger($attributes)
{
return array_map(fn($v) => $v === false ? 0 : ($v === true ? 1 : $v), $attributes);
}
Run Code Online (Sandbox Code Playgroud)
然后我们:
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)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4996 次 |
最近记录: |