Some of the testing I will need to do will require comparing a known array with the result I am getting from the functions I will be running.
For comparing arrays recursively:
Use the sort() function to sort an array element and then use the equality operator. Use array operator ( == ) in case of Associative array.
The array_diff() function compares the values of two (or more) arrays, and returns the differences. This function compares the values of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2 or array3, etc.
Yes it does. assertEquals()
and assertNotEquals()
documentation.
Specifically:
assertEquals()
assertEquals(mixed $expected, mixed $actual[, string $message = ''])
Reports an error identified by
$message
if the two variables$expected
and$actual
are not equal.
assertNotEquals()
is the inverse of this assertion and takes the same arguments.
Test Code:
public function testArraysEqual() { $arr1 = array( 'hello' => 'a', 'goodbye' => 'b'); $arr2 = array( 'hello' => 'a', 'goodbye' => 'b'); $this->assertEquals($arr1, $arr2); } public function testArraysNotEqual() { $arr1 = array( 'hello' => 'a', 'goodbye' => 'b'); $arr2 = array( 'hello' => 'b', 'goodbye' => 'a'); $this->assertNotEquals($arr1, $arr2); }
[EDIT]
Here is the code for out of order aLists:
public function testArraysEqualReverse() { $arr1 = array( 'hello' => 'a', 'goodbye' => 'b'); $arr2 = array( 'goodbye' => 'b', 'hello' => 'a'); $this->assertEquals($arr1, $arr2); }
This test fails:
public function testArraysOutOfOrderEqual() { $arr1 = array( 'a', 'b'); $arr2 = array( 'b', 'a'); $this->assertEquals($arr1, $arr2); }
With message:
Failed asserting that Array ( [0] => b [1] => a ) is equal to Array ( [0] => a [1] => b )
@wilmoore
$array1 = array('hi','hi2'); $array2 = array('hi2','hi'); $this->assertEquals(array_values($array1), array_values($array2));
Will fail.
@Ben Dauphinee
It might be worth looking at assertContains(mixed $needle, array $haystack)
but you would have to loop through both arrays and compare each element with the other array to ensure it contained all the required elements and no others, this however wouldn't account for an array containing two identical elements
$array1 = array('hi','hi2','hi'); $array2 = array('hi2','hi');
would pass in this case
It also doesn't account for any further recursion which would probably be quite complicated to deal with.
Depending on the complexity might just be easier in the long run to implement your own assert function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With