Question

J'ai deux tableaux qui sont censés être égaux.

Lorsque Var Dumping et affirmant si ceux-ci sont égaux, j'obtiens la sortie suivante

array(2) {
  [0]=>
  array(3) {
    ["100"]=>         //notice that the key is NOT numeric
    int(0)
    ["strKey1"]=>
    int(0)
    ["strKey2"]=>
    int(0)
  }
  [1]=>
  array(3) {
    ["100"]=>         //notice that the key is NOT numeric
    int(0)
    ["strKey1"]=>
    int(0)
    ["strKey2"]=>
    int(0)
  }
}
There was 1 failure:

1) Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
Array (
-    '100' => 0
     'strKey1' => 0
     'strKey2' => 0
+    '100' => 0
 )

Une boucle FOREAK simple pour les deux tableaux cartographiant les clés à nouveau numériques, fonctionne bien, mais n'est pas le plus joli piratage d'un test.

    $actualArray = array();

    foreach ($actualOriginal as $key => $value) {
        $actualArray[$key] = $value;    
    }

    $expectedArray = array();

    foreach ($expectedOriginal as $key => $value) {
        $expectedArray[$key] = $value;    
    }

Des suggestions pour lesquelles ces tableaux ne sont pas considérés comme égaux?

Merci pour toute aide!

Était-ce utile?

La solution

Je ne sais qu'une seule façon d'obtenir des touches de chaîne numériques: en convertissant l'objet en tableau

$object = new stdClass();
$object->{'100'} = 0;
$object->strKey1 = 0;
$object->strKey2 = 0;
$array1 = (array) $object;
var_dump($array1);
//array(3) {
//  '100' => -- string
//  int(0)
//  'strKey1' =>
//  int(0)
//  'strKey2' =>
//  int(0)
//}

Ainsi, $ array1 n'est pas égal à ce $ array2

$array2 = array('100' => 0, 'strKey1' => 0, 'strKey2' => 0,);
var_dump($array2);
//array(3) {
//  [100] => -- integer
//  int(0)
//  'strKey1' =>
//  int(0)
//  'strKey2' =>
//  int(0)
//}
var_dump($array1 == $array2);
//bool(false)

Ce n'est pas un bug: https://bugs.php.net/bug.php?id=61655


Phpunit a également ses propres règles de comparaison.

$this->assertEquals($array1, $array1); // Fail
$this->assertEquals($array1, $array1); // Pass

https://github.com/sebastianbergmann/phpunit/blob/3.7/phpunit/framework/comparator/array.php

Brève description de la comparaison du phpunit:

$expected = $array1;
$actual = $array1;

$remaining = $actual;
$equal = TRUE;
foreach ($expected as $key => $value){
    unset($remaining[$key]);} // string numeric keys would not be unsetted.

if ($remaining)
    $equal = FALSE;

var_dump($equal);
//bool(false)

Alors ... vous faites bien. Pour obtenir un tableau "normal", vous devez recréer un tableau. Vous pouvez utiliser ForEach. Mais le Wather Way consiste à utiliser les fonctions de sérialisation.

$this->assertEquals(unserialize(serialize($array1)), unserialize(serialize($array1)));
//Pass

Mais cela ne semble pas beaucoup mieux. : ^)

Vous pouvez également utiliser assertSame.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top