【发布时间】: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