【问题标题】:phpunit fails asserting that two arrays are equal, but shows no differencephpunit 无法断言两个数组相等,但没有显示差异
【发布时间】:2015-05-06 01:37:24
【问题描述】:

这是 phpunit 所说的:

1) Asgard\Entity\Tests\EntityTest::testToArray
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
 Array (
     'id' => null
     'title' => 'Test Title'
     'content' => 'Test Content'
     'published' => 2015-03-04T11:19:50+0000
     'comments' => Array (
         0 => Array (
             'id' => null
             'content' => 'foo'
             'published' => 2015-03-04T11:19:50+0000
             'another_property' => null
             'news' => null
         )
         1 => Array (
             'id' => null
             'content' => 'bar'
             'published' => 2015-03-04T11:19:50+0000
             'another_property' => null
             'news' => null
         )
         2 => Array (
             'id' => null
             'content' => 'baz'
             'published' => 2015-03-04T11:19:50+0000
             'another_property' => null
             'news' => null
         )
     )
     'another_property' => null
 )

https://travis-ci.org/asgardphp/asgard/jobs/53029084

“预期”和“实际”之间没有区别。测试通常会通过,但有时会失败。

【问题讨论】:

  • php 5.6 的测试总是失败?
  • 到目前为止是的,我只看到它在 php 5.6 中失败
  • 我还没有 php 5.6。对于 5.5 和 5.3,我无法复制您的问题。

标签: php phpunit


【解决方案1】:

由于您在测试中使用 DateTime - 您确定您没有得到在一秒钟内开始并在另一秒钟内完成的测试,因此时间戳会根据您查看的阶段而有所不同吗? - 在测试中使用动态日期和时间是偶尔测试失败的常见原因。

【讨论】:

  • datetime 对象只生成一次,用于实际结果和预期结果。无论如何,即使这是问题所在,phpunit 也应该显示出预期/实际之间的差异。
  • 非常感谢,如果没有日期时间可能导致问题的提示,我会浪费数小时。不过我的问题有点不同,我使用了 laravel (Carbon) 的默认转换,它在使用不同的格式 (iso8601) 后工作。
【解决方案2】:

发现问题。元素的顺序不同。虽然输出没有显示,但有点烦人。

我已将 assertEquals 替换为:

$this->assertTrue($this->similar_arrays($arr1, $arr2));

protected function similar_arrays($a, $b) {
    if(is_array($a) && is_array($b)) {
        if(count(array_diff(array_keys($a), array_keys($b))) > 0)
            return false;

        foreach($a as $k => $v) {
            if(!$this->similar_arrays($v, $b[$k]))
                return false;
        }

        return true;
    }
    else
        return $a === $b;
}

【讨论】:

    【解决方案3】:

    检查您的值中是否包含 EOL。

    如果你有这样的值:

    'x' => 'line1
    

    line2'

    改成

    'x' => "line1\nline2"
    

    注意:这可能无法直接回答 OP 遇到的问题,但这对我有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-07
      • 2021-02-25
      • 2011-04-19
      • 2020-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多