Laravel Eloquent, assert that collection contains item
Asked Answered
S

2

24

How to assert (in PHPUnit test) that Eloquent collection contains an item?

Something like this:

$expected = factory::create(Item::class)->create();
$eloquentCollection = someData(); // Item::orderBy(...)->...->get();
$this->assertContains($expected, $eloquentCollection);
Selle answered 8/12, 2016 at 12:33 Comment(0)
G
51

You can use the contains method to assertTrue the test as:

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

You may also pass a key / value pair to the contains method, which will determine if the given pair exists in the collection:

$this->assertTrue($eloquentCollection->contains('id', $expected->id));
Grandiose answered 8/12, 2016 at 14:0 Comment(2)
Yes, looks like it works. But it is more messy :( I thought there are already built-in asserts for that.Selle
I don't think there is any built-in function for this. And it is how we mostly do assertion. Somehow I find it more readable.Grandiose
S
0

In later versions of PHPUnit (8.5, 9.6, 10.4) there is assertContains.

$needle = 'a';
$haystack = ['a', 'b', 'c'];
$this->assertContains($needle, $haystack);

https://docs.phpunit.de/en/8.5/assertions.html#assertcontains https://docs.phpunit.de/en/9.6/assertions.html#assertcontains https://docs.phpunit.de/en/10.4/assertions.html#assertcontains

Sample answered 8/11, 2023 at 22:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.