我注意到将protected dates数组中的 Date Mutator 字段设置到模型中,其中使用的日期格式Faker被修改为Carbon对象,并且不返回 ; 中设置的格式Faker。这是正常的吗?
为了解释这个问题,模型类似于:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Post extends Model
{
use HasFactory;
protected $dates = [
'seen_at'
];
// other code here...
}
该类Factory包含:
<?php
namespace App\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
use App\Models\Post;
class PostFactory extends Factory
{
protected $model = Post::class;
public function definition()
{
return [
'number' => $this->faker->randomDigit,
'seen_at' => $this->faker->date($format = 'Y-m-d\TH:i:s.vP', $max = 'now'),
'quality' => $this->faker->unique()->regexify('[A-D][A-D]'),
];
}
}
Test课程是:
<?php
namespace App\Tests\Feature;
use Tests\TestCase;
use App\Factories\PostFactory;
class PostControllerTest extends TestCase
{
public function setUp(): void
{
parent::setUp();
$post = PostFactory::new()->make();
dd($post->seen_at);
// other code here....
}
}
运行测试,dd()返回:
Illuminate\Support\Carbon @228109214 {#2283
#constructedObjectId: "00000000486a8e5f00000000514b58c9"
#localMonthsOverflow: null
#localYearsOverflow: null
#localStrictModeEnabled: null
#localHumanDiffOptions: null
#localToStringFormat: null
#localSerializer: null
#localMacros: null
#localGenericMacros: null
#localFormatFunction: null
#localTranslator: null
#dumpProperties: array:3 [
0 => "date"
1 => "timezone_type"
2 => "timezone"
]
#dumpLocale: null
date: 1977-03-25 03:40:14.0 +00:00
}
与date指定的格式不匹配Faker,应该是'Y-m-d\TH:i:s.vP';但是是1977-03-25 03:40:14.0 +00:00。
如果我seen_at从protected $dates数组中删除,再次运行测试输出是正确的:
"1970-02-10T03:13:34.000+00:00"
另一个想法是,如果我dd()生成整个模型,Faker其中protected $dates包含seen_at:
class PostControllerTest extends TestCase
{
public function setUp(): void
{
parent::setUp();
$post = PostFactory::new()->make();
dd($post);
// other code here....
}
}
它包含正确日期的输出:
App\Models\Post {#2399
#table: "post"
. . .
#attributes: array:39 [
"number" => 8
"seen_at" => "1970-02-10T03:13:34.000+00:00"
"quality" => "AB"
]
. . .
#guarded: array:1 [
0 => "*"
]
}
这种行为正常吗?如果“是”,我怎样才能返回正确的日期格式?
谢谢你。