views:

40

answers:

2

What is a good way to assert that two arrays of objects are equal, when the order of the elements in the array is unimportant, or even subject to change?

+1  A: 

If the array is sortable, I would sort them both before checking equality. If not, I would convert them to sets of some sort and compare those.

Rodney Gitzel
+1  A: 

The cleanest way to do this would be to extend phpunit with a new assertion method. But here's an idea for a simpler way for now. Untested code, please verify:

Somewhere in your app:

 /**
 * Determine if two associative arrays are similar
 *
 * Both arrays must have the same indexes with identical values
 * without respect to key ordering 
 * 
 * @param array $a
 * @param array $b
 * @return bool
 */
function arrays_are_similar($a, $b) {
  // if the indexes don't match, return immediately
  if (count(array_diff_assoc($a, $b))) {
    return false;
  }
  // we know that the indexes, but maybe not values, match.
  // compare the values between the two arrays
  foreach($a as $k => $v) {
    if ($v !== $b[$k]) {
      return false;
    }
  }
  // we have identical indexes, and no unequal values
  return true;
}

In your test:

$this->assertTrue(arrays_are_similar($foo, $bar));
Craig
Craig, you're close to what I tried originally. Actually array_diff is what I needed, but it doesn't seem to work for objects. I did write my custom assertion as explained here: http://www.phpunit.de/manual/current/en/extending-phpunit.html
koen