由于 1 秒的差异,Laravel 测试间歇性失败

ker*_*rin 3 laravel

我对我的应用程序中的大多数模型进行了以下类型的测试:

     * @test
     */
    public function an_authorised_user_can_delete_a_contact()
    {
        $contact = Contact::factory()->create();
        $this->assertDatabaseHas('contacts', $contact->getAttributes());

        $response = $this->actingAs($this->user_delete)
            ->delete('/contacts/'.$contact->id);

        $this->assertSoftDeleted('contacts', $contact->getAttributes());

        $response->assertRedirect('contacts');
    }
Run Code Online (Sandbox Code Playgroud)

这在大多数情况下都运行良好,但有时会由于时间戳稍有偏差而失败。

无法断言表 [联系人] 中的任何软删除行与属性 {"first_name":"Katherine","last_name":"Will","title":"Jewelry Model OR Mold Makers","telephone":" 匹配+15127653255","手机":"+19366193055","电子邮件":"lucy.lind@example.net","vendor_id":1,"updated_at":"2022-04-04 18:09:50", “created_at”:“2022-04-04 18:09:50”,“id”:1}。

找到:[ {“id”:1,“first_name”:“Katherine”,“last_name”:“Will”,“title”:“珠宝模型或模具制造商”,“电话”:“+15127653255”,“手机” :“+19366193055”,“电子邮件”:“lucy.lind@example.net”,“vendor_id”:1,“created_at”:“2022-04-04 18:09:50”,“updated_at”:“2022- 04-04 18:09:51", "deleted_at": "2022-04-04 18:09:51" } ]

区别在于updated_at- “2022-04-04 18:09:50”与“2022-04-04 18:09:51”。

是否有更好的方法来构建测试以使其更加稳健?

小智 6

第一个解决方案:

使用Carbon::setTestNow('2022-04-04 18:09:50'),这将使时间戳不改变。

第二种解决方案(推荐):

由于您编写了测试来检查授权用户是否可以删除联系人,因此我不会像您那样检查所有属性,而是会断言模型本身(laravel 文档中建议这样做),链接如下

$this->assertSoftDeleted($contact);
Run Code Online (Sandbox Code Playgroud)

或者只检查 id

$this->assertSoftDeleted('contacts', [
    'id' => $contact->id
]);
Run Code Online (Sandbox Code Playgroud)

您也可以在 laracast 论坛上查看这个答案,也许它会对您有更多帮助。