问题
我有一个表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
1条答案
按热度按时间ogsagwnx1#
你可以在
TestCase
类中编写一个方法,如下所示:然后我们: