Laravel 10升级至11后单元测试日期验证失败求助
问题:Laravel 11升级后日期验证单元测试失败
收到的错误信息
DateMalformedStringException: Failed to parse time string (abc) at position 0 (a): The timezone could not be found in the database
测试失败详情
// ... FAILED Tests\Feature\Profile\UpdateTest > birthday is not date Session is missing expected key [errors]. Failed asserting that false is true. The following exception occurred during the last request: DateMalformedStringException: Failed to parse time string (abc) at position 0 (a): The timezone could not be found in the database in /home/runner/work/New-Official-Website/New-Official-Website/vendor/nesbot/carbon/src/Carbon/Traits/Creator.php:100 Stack trace: // ... Cannot create dynamic property DateMalformedStringException::$xdebug_message // ...
验证规则(required和before_or_equal规则测试已通过)
<?php namespace App\Http\Requests\Profile; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Rule; class UpdateRequest extends FormRequest { //... public function rules(): array { // ... 'birthday' => 'required|date|before_or_equal:'.now()->subYears(2)->format('Y-m-d'), // ... } // ... }
测试代码
<?php namespace Tests\Feature\Profile; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\TestCase; class UpdateTest extends TestCase { use RefreshDatabase; private $happyCase = [ 'username' => 'testing123', 'family_name' => 'Chan', 'given_name' => 'Diamond', 'passport_type_id' => 2, 'passport_number' => 'A1234567', 'gender' => 'Male', 'birthday' => '1997-07-01', ]; // ... public function test_birthday_is_not_date() { $data = $this->happyCase; $data['birthday'] = 'abc'; $response = $this->actingAs($this->user)->put(route('profile.update'), $data); $response->assertInvalid(['birthday' => 'The birthday field must be a valid date.']); } // ... }
环境差异
本地Laravel 10环境测试可正常通过,仅在Laravel 10升级至11的PR中出现此错误。
内容的提问来源于stack exchange,提问作者黃梓榆
相关产品推荐
相关产品推荐

