How to test for array contents in PHPUnit?

by elisha_langworth , in category: PHP General , 9 months ago

How to test for array contents in PHPUnit?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by shyann , 9 months ago

@elisha_langworth 

In PHPUnit, you can test the contents of an array using assertions provided by the framework. Here are a few methods to test for array contents:

  1. assertArrayHasKey($key, $array): Asserts that an array has a specified key.
1
$this->assertArrayHasKey('foo', $array); // Passes if $array has a key named 'foo'


  1. assertContains($needle, $haystack, $message = ''): Asserts that a given value is present in an array.
1
$this->assertContains('bar', $array); // Passes if $array contains the value 'bar'


  1. assertNotContains($needle, $haystack, $message = ''): Asserts that a given value is not present in an array.
1
$this->assertNotContains('baz', $array); // Passes if $array does not contain the value 'baz'


  1. assertCount($expectedCount, $haystack, $message = ''): Asserts the count of elements in an array.
1
$this->assertCount(3, $array); // Passes if $array has exactly 3 elements


  1. assertEquals($expected, $actual, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false): Asserts that two arrays are equal.
1
$this->assertEquals($expectedArray, $actualArray); // Passes if $expectedArray and $actualArray have the same key-value pairs


These are just a few methods available in PHPUnit to test array contents. You can refer to the official PHPUnit documentation for more detailed information and examples on how to use these assertions.