views:

137

answers:

1

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?
+1  A: 

Yes it does. PHPUnit API Assert.

Specifically:

void assertEquals(array $expected, array $actual)

Reports an error if the two arrays $expected and $actual are not equal.

void assertEquals(array $expected, array $actual, string $message)

Reports an error identified by $message if the two arrays $expected and $actual are not equal.

void assertNotEquals(array $expected, array $actual)

Reports an error if the two arrays $expected and $actual are equal.

void assertNotEquals(array $expected, array $actual, string $message)

Reports an error identified by $message if the two arrays $expected and $actual are equal.

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
)
Gutzofter
@Gutzofter Is this a function that requires the arrays being compared to be in exactly the same order key for key?
Ben Dauphinee
Interesting question...
Gutzofter
@Gutzofter So if I want to test an out of order array against a known good, I will have to make sure the keys match, but that is the only caveat? Thanks for the help!
Ben Dauphinee