gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 15:54:30 24 4
gpt4 key购买 nike

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

     * @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');
}

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

Failed asserting that any soft deleted row in the table [contacts] matches the attributes {"first_name":"Katherine","last_name":"Will","title":"Jewelry Model OR Mold Makers","telephone":"+15127653255","mobile":"+19366193055","email":"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}.

Found: [{"id": 1,"first_name": "Katherine","last_name": "Will","title": "Jewelry Model OR Mold Makers","telephone": "+15127653255","mobile": "+19366193055","email": "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”。

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

最佳答案

第一个解决方案:

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

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

由于您编写了测试来检查授权用户是否可以删除联系人,所以我不会像您那样检查所有属性,而是断言模型本身,这在 laravel 文档中推荐,here's the link :

$this->assertSoftDeleted($contact);

或者只检查id

$this->assertSoftDeleted('contacts', [
'id' => $contact->id
]);

您还可以查看 this answer在 laracast 论坛上,也许它对您有更多帮助。

关于由于 1 秒的差异,Laravel 测试间歇性失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71734326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com