我有两个阵列应该相等。

当var倾倒并断言是否相等时,我将获得以下输出

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
 )

一个简单的for循环,用于两个阵列映射键再次数字,工作正常,但不是测试中最漂亮的黑客攻击。

    $actualArray = array();

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

    $expectedArray = array();

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

有什么建议为什么这些阵列不相等?

谢谢你的帮助!

有帮助吗?

解决方案

我只知道如何获取数字字符串键:通过将对象转换为数组

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

因此,$ array1不等于此$ 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)

这不是一个错误: https://bugs.php.net/bug.php?id=61655


phpunit也有自己的比较规则。

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

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

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)

所以...你做对了。要获取“正常”数组,您需要重新创建数组。您可以使用foreach。但是Shoter Way是使用序列化功能。

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

但这看起来并不好。 :^)

您也可以使用 assertSame.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top