Laravel Eloquent,断言集合包含项目

Laravel Eloquent, assert that collection contains item

如何断言(在 PHPUnit 测试中)Eloquent 集合包含一个项目?

像这样:

$expected = factory::create(Item::class)->create();
$eloquentCollection = someData(); // Item::orderBy(...)->...->get();
$this->assertContains($expected, $eloquentCollection);

您可以使用 contains 方法来 assertTrue 测试:

$this->assertTrue($eloquentCollection->contains($expected));

您还可以将键/值对传递给 contains 方法,该方法将确定给定对是否存在于集合中:

$this->assertTrue($eloquentCollection->contains('id', $expected->id));