【问题标题】:Test fails because of date time formatting when searching for model in database在数据库中搜索模型时,由于日期时间格式测试失败
【发布时间】:2019-03-22 00:47:52
【问题描述】:

自 Laravel 5.6 起,Eloquent Date Casting 可用。
所以我有一个模型 MyModel

class MyModel extends Model {
    protected $casts = ['from' => 'date:Y-m-d', 'to' => 'date:Y-m-d'];
    protected $dates = ['from', 'to'];
}

还有工厂:

$factory->define(MyModel::class, function(Faker $faker) {
    return [
        'from' => Carbon::instance($faker->dateTime),
        'to' => Carbon::instance($faker->dateTime),
        // some more attributes
    ];
}

在我的单元测试中,我正在寻找 MyModel 的实例:

/** @test */
public function example() {
    $myModel = factory(MyModel::class)->create();

    $this->assertDatabaseHas('my_models', $myModel->attributesToArray());
}

这就是我得到的(摘录):

断言表 [my_models] 中的行与属性 {
匹配失败 “来自”:“2019-01-12”,
“致”:“2019-02-13”,
}.
找到:[{
“来自”:“2019-01-12 00:00:00”,
“至”:“2019-02-13 00:00:00”,
}]。

显然测试失败了,因为时间附加在数据库记录的字段中。它们的类型为date

我可以将断言更新为这样的内容...

$this->assertDatabaseHas('my_models', [
    'from' => $myModel->from->toDateTimeString(),
    'to' => $myModel->to->toDateTimeString(),
] + $myModel->attributesToArray());

...但这远非优雅。

我该怎么做才能使这个断言成功?

【问题讨论】:

  • 能否添加完整的测试代码?
  • @DouwedeHaan 我已经添加了一些代码!

标签: php laravel phpunit


【解决方案1】:

我最终编写了一个新的断言方法,它将模型的日期属性格式化为 Y-m-d H:i:s 以进行正确比较:

protected function assertDatabaseHasModel(string $table, Model $model, ?string $connection = null): void
{
    $attributes = $model->attributesToArray();
    $reflection = new ReflectionClass($model);
    $property = $reflection->getProperty('casts');
    $property->setAccessible(true);

    collect($property->getValue($model))->each(function (string $cast, string $field) use ($model, &$attributes) {
        if (Str::startsWith($cast, 'date:')) {
            $attributes[$field] = $model->$field->toDateTimeString();
        } elseif (in_array($cast, ['array', 'object'], true) && $model->$field !== null) {
            $attributes[$field] = $this->castAsJson($model->$field);
        }
    });

    $this->assertDatabaseHas($table, $attributes, $connection);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-02
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    相关资源
    最近更新 更多