Pregunta

Tengo dos matrices que se supone que son iguales.

Cuando Var dumping y afirme si son iguales, obtengo la siguiente salida

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
 )

Un bucle de Foreach simple para las dos matrices que mapean las claves para ser numéricas nuevamente, funciona bien, pero no es el truco más bonito dentro de una prueba.

    $actualArray = array();

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

    $expectedArray = array();

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

¿Alguna sugerencia por qué estas matrices no se consideran iguales?

¡Gracias por cualquier ayuda!

¿Fue útil?

Solución

Sé solo una forma de obtener teclas de cadena numérica: convirtiendo el objeto en matriz

$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)
//}

Entonces, $ array1 no es igual a este $ 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)

No es un error: https://bugs.php.net/bug.php?id=61655


También Phpunit tiene sus propias reglas de comparación.

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

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

Descripción breve de la comparación de 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)

Entonces ... lo haces bien. Para obtener una matriz "normal", debe recrear una matriz. Podrías usar foreach. Pero Shoter Way está en el uso de funciones de serialización.

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

Pero no se ve mucho mejor. :^)

También podrías usar assertSame.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top