assertDatabaseHas在phpunit测试中不起作用

assertDatabaseHas在phpunit测试中不起作用

本文介绍了Laravel assertDatabaseHas在phpunit测试中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

/** @test */
    public function it_updates_customer_status_to_deactivated_for_admin_users()
    {
        $this->hubAdminUser = factory(User::class)->state('admin')->create();
        $this->customer = Customer::first();
        $this->customer->status_id = 2; //active
        $this->customer->save();

        // this will update status_id to 3
        $this->actingAs($this->hubAdminUser)
            ->patch(route('hub.customer.updateStatus', $this->customer))
            ->assertRedirect();

        $this->assertDatabaseHas('tenants', [
            'id' => $this->customer->id,
            'status_id' => 3, //deactivated
        ]);
    }

-> patch(route('hub.customer.updateStatus',$ this-> customer))行将 status_id 的值从2更改为到3,这绝对是我在[code>-> assertRedirect(); 之后尝试过的 $ this-> customer-> refresh()-> status_id 行,这给了我3.这失败了,因为它说客户的 status_id 在数据库中设置为2.有什么想法可以解决这个问题吗?

The ->patch(route('hub.customer.updateStatus', $this->customer)) line will change the value of status_id from 2 to 3 which it definitely does as I have even tried $this->customer->refresh()->status_id after the ->assertRedirect(); line and that gives me 3. This is failing as it says that the customer's status_id is set to 2 in the database. Any ideas how I can fix this?

推荐答案

我建议您将 assertDatabaseHas 更改为 assertEquals .

这是原因:

""使用Eloquent时,您可以指定一个表名-否则表名会自动计算出来.然后,您会忘记它.因此,它是为您而设计的,无需知道表的名称."

"那么,Laravel被设计了,因此我们不必知道数据库表的名称.使用 assertDatabaseHas ,您每次使用时都必须知道该表的名称."

"Laravel is architected, then, so that we don’t have to know the names of our database tables. With assertDatabaseHas you have to know the name of the table every time you use it."

"但是,我认为最好在不需要时停止直接针对数据库断言.特别是由于您的代码通常不是在Laravel中设计为直接处理数据库,因此为什么要进行测试?留在您的域中并测试输入和输出值,而不是实现."

摘自文章 https://www.aaronsaray.com/2020/stop-assert-database-has-laravel

这篇关于Laravel assertDatabaseHas在phpunit测试中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 02:14