【问题标题】:Unit Testing with Model::Find Fails in Laravel在 Laravel 中使用 Model::Find 进行单元测试
【发布时间】:2020-10-22 22:57:50
【问题描述】:

我正在为我相当大的 Laravel 应用程序创建单元测试。

此测试通过所有断言。它为广告状态模型创建一个新的数据库条目。

/** @test **/
public function create_a_new_advertising_status_test()
{
    $status = AdvertisingStatus::create(['name' => 'Test']);
    $this->assertNotNull($status);
    $this->assertCount(1, AdvertisingStatus::all());
    $this->assertEquals($status->name, $this->advertisingStatus['name']);
}

此测试未通过 NotNull 断言,因为它说 $status 为 null,这意味着 Find 方法失​​败。

/** @test **/
public function edit_an_existing_advertising_status_entry()
{
    $status = AdvertisingStatus::create(['name' => 'Test']);
    // $status = AdvertisingStatus::first(); // This successfully finds the database entry
    $status = AdvertisingStatus::find(1); // This fails to find the database entry
    $status->name = 'Edit';
    $status->save();

    $this->assertNotNull($status);
    $this->assertCount(1, AdvertisingStatus::all());
    $this->assertEquals($status->name, "Edit");
}

它看起来像 find 函数,随后 where 函数需要很长时间才能找到条目,因此测试将 $status 变量呈现为 null。

除了使用Model::first() 函数之外,有没有人知道如何克服这个问题?

我想知道是不是因为我的应用程序非常大并且需要很长时间才能运行,因为我使用的是RefreshDatabase

【问题讨论】:

  • first() 和 find(1) 并不完全相同。 first 是最低的 id,find(1) 是 id = 1。试试 dd(AdvertisingStatus::first()) 看看 id 是什么!
  • @KurtFriars 它是 1。每次运行测试时都会刷新数据库,因此没有条目。我还检查了 var_dump,它显示的 id 为 1。
  • 那时真的很奇怪。希望你能找到解决办法!

标签: laravel unit-testing phpunit


【解决方案1】:

你必须先创建一个工厂,然后你会这样使用它:

   $status = factory(AdvertisingStatus::class)->create(['name' => 'Test']);

【讨论】:

  • 考虑到它只是返回一个包含填充字段的模型,我不知道工厂将如何使其工作。不过,我会试一试
  • 我更新我的答案:)
  • create 方法返回对象,因此无需保存。当我更改对象的名称时,必须保存它,因此保存它。问题在于 find 方法,而不是我的逻辑顺序,因为 first() 方法返回正确的对象。我认为这与它需要很长时间才能找到对象有关
  • 太棒了。所以如果工厂已经工作,请标记为已解决
  • 是的,肯定的。我混淆了Create()firstOrNew()
猜你喜欢
  • 1970-01-01
  • 2022-08-09
  • 2018-03-04
  • 1970-01-01
  • 1970-01-01
  • 2017-05-15
  • 2013-09-13
  • 2021-06-26
  • 2014-05-11
相关资源
最近更新 更多