[wp-unit-tests] [WordPress Unit Tests] #130: Introduce assertion for comparing sets

WordPress Trac wp-trac at lists.automattic.com
Fri Sep 21 01:14:22 UTC 2012


#130: Introduce assertion for comparing sets
--------------------+----------------------------
 Reporter:  scribu  |       Type:  enhancement
   Status:  new     |   Priority:  normal
Milestone:          |  Component:  Test Framework
 Keywords:          |
--------------------+----------------------------
 There are a lot of cases when you want to check a collection of items,
 disregarding the order of the elements.

 This type of collection is called a set (in PHP, the closes thing we have
 to sets is numeric arrays).

 For example, say you have these values.

 {{{
 $expected = array( 'apple', 'orange', 'pear' );
 $actual = array( 'banana', 'apple', 'orange' );
 }}}

 You could just use assertEquals(), with a special parameter that sorts the
 arrays before comparing:

 {{{
 $this->assertEquals( $expected, $actual, '', 0, 10, true );
 }}}

 {{{
 Failed asserting that two arrays are equal.
 --- Expected
 +++ Actual
 @@ @@
  Array (
      0 => 'apple'
 -    1 => 'orange'
 -    2 => 'pear'
 +    1 => 'banana'
 +    2 => 'orange'
  )
 }}}

 Ugh... you can't really see what's going on there.

 What you really want to know is if there are any items in $expected which
 are not in $actual and vice-versa:

 {{{
 $missing = array_diff( $expected, $actual );
 $extra = array_diff( $actual, $expected );

 $this->assertEquals( $expected, $actual );
 }}}

 {{{
 Failed asserting that two arrays are equal.
 --- Expected
 +++ Actual
 @@ @@
  Array (
 -    0 => 'banana'
 +    2 => 'pear'
  )
 }}}

 Much better!

 When the sets are equal, you'll be comparing two empty arrays, so it all
 works out.

-- 
Ticket URL: <https://unit-test.trac.wordpress.org/ticket/130>
WordPress Unit Tests <https://unit-test.trac.wordpress.org>
My example project


More information about the wp-unit-tests mailing list