使用模型::查找在 Laravel 中进行单元测试失败



我正在为我相当大的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

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

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

最新更新