我的表 sample 包含has_value和has_condition列,它们是laravel在MySQL中创建的布尔类型。在 sample 表的Factory中,我将faker值设置为boolean。在测试用例中,我按原样通过了造假者值。 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
答案 0 :(得分:0)
因为测试类中的比较使用严格比较(===)
例如,如果您尝试:
<a href="@Url.Action("FaveUnfave", new { id = data.ID})" class="btn-link glyphicon glyphicon-heart-empty"></a>
它将失败,同时:
$this->assertTrue(1);
将通过...。
要解决这种情况,您必须根据以下条件使用assertEqual进行比较:
$this->assertTrue(true);
将通过...
返回您的代码:
代替
$this->assertEquals(1,true);
您可以使用:
$this->assertDatabaseHas('sample', $data);