7

I'm writing some unit tests using phpunit and I now want to assert that an array contains a certain value, but the only function I can find is assertArrayHasKey(). There is no assertArrayHasValue whatsoever.

So to be clear I want something like this:

$a = [5, 8, 16];
assertArrayHasValue(8, $a);

All tips are welcome!

kramer65
  • 50,427
  • 120
  • 308
  • 488
  • Here is a list of assertion as well, maybe it will help. http://stackoverflow.com/questions/569369/list-of-all-phpunit-assertions – Heath N May 22 '14 at 16:17
  • Possible duplicate of [test if array contains value using PHPUnit](https://stackoverflow.com/questions/31638220/test-if-array-contains-value-using-phpunit) – TIGER Jul 31 '17 at 06:03

2 Answers2

8

You can do it with function assertContains()

try this:

$a = [5, 8, 16];
$this->assertContains(8, $a);

ASSERT_CONTAINS

Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
2

You can use ouzo goodies library.

 $animals = ['cat', 'dog', 'pig'];
 Assert::thatArray($animals)->hasSize(3)->contains('cat');

There are a lot of interesting assertions that can be chained e.g.

Assert::thatArray($users)->onMethod('getAge')->containsOnly(35, 24);

See http://ouzo.readthedocs.org/en/latest/documentation/tests.html#array-assertions

woru
  • 1,420
  • 9
  • 17