【问题标题】:Laravel assertDatabaseHas in phpunit test is not workingphpunit 测试中的 Laravel assertDatabaseHas 不起作用
【发布时间】:2020-11-13 06:23:30
【问题描述】:

我有以下代码:

/** @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,这肯定是因为我什至在->assertRedirect(); 行之后尝试了$this->customer->refresh()->status_id,这给了我 3。正如它所说,这失败了客户的status_id 在数据库中设置为2。有什么想法可以解决这个问题吗?

【问题讨论】:

  • Customer 模型的表名是tenants?
  • 是的,没错。它是这个包的一部分:tenancyforlaravel.com/docs/v2/getting-started
  • 您如何确定这将有效"// this will update status_id to 3"?我会在上面添加assertStatus(200),或者如果你要返回一些东西,我会断言..
  • 没有足够的信息来真正帮助您,唯一想到的是,如果您为租户使用多个数据库,assertDatabaseHas() 可能使用了错误的数据库连接。跨度>
  • assertDatabaseHas() 很有可能正在工作,并且测试成功地告诉您代码没有按照您的预期工作。 hub.customer.updateStatus 的控制器中发生了什么?

标签: database laravel unit-testing testing phpunit


【解决方案1】:

我建议您将assertDatabaseHas 更改为assertEquals

原因如下:

“当你使用 Eloquent 时,你可以指定一个表名——或者它会自动计算出来。然后你就忘了它。所以,它的理想设计是让你不必知道表名桌子。”

“Laravel 是经过架构设计的,因此我们不必知道数据库表的名称。使用assertDatabaseHas,您每次使用时都必须知道表的名称。”

“但是,我认为最好在不需要时停止直接针对数据库进行断言。特别是因为您的代码通常不会在 Laravel 中构建以直接处理数据库,为什么要进行测试呢?留在您的领域并测试输入和输出值,而不是实现。”

来自https://www.aaronsaray.com/2020/stop-assert-database-has-laravel的一篇文章

【讨论】:

  • 你能引用那篇文章的相关摘录吗?链接往往会随着时间的推移而消失
猜你喜欢
  • 2018-10-29
  • 1970-01-01
  • 2019-07-20
  • 2013-11-05
  • 2015-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-12
相关资源
最近更新 更多