Search code examples
phpunit-testingrecursionmultidimensional-arrayphpunit

Does PHPUnit have some inbuilt recursive array comparison function?


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:

  • Does PHPUnit have an inbuilt function?
  • Does someone here have some code they have constructed to share?
  • Will this be something I will have to construct on my own?

Solution

  • 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);
    }
    

    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
    )