为什么PHPUnit会为明显相同的字符串给我一个assertEquals失败?

时间:2011-12-19 03:12:36

标签: php phpunit

以下脚本演示和文档(在标题注释中),即我无法检测到“预期”和“实际”字符串之间的任何差异:

<?php

/*
$ phpunit MyTest.php
PHPUnit 3.4.0 by Sebastian Bergmann.

F

Time: 0 seconds

There was 1 failure:

1) MyTest::test_print_r
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-O:7:"MyClass":2:{s:13:"MyClassvar3";N;s:4:"var1";N;}
+O:7:"MyClass":2:{s:13:"MyClassvar3";N;s:4:"var1";N;}

.../MyTest.php:41
.../bin/phpunit:54

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
*/

class MyClass {
    static protected $var2;
    private $var3;
    public $var1;

    public function foo($item) {
        echo $item . "\n";
    }
}

class MyTest extends PHPUnit_Framework_TestCase {
    function test_print_r() {
        $m = new MyClass();
        $this->assertEquals(trim('O:7:"MyClass":2:{s:13:"MyClassvar3";N;s:4:"var1";N;}'), trim(serialize($m)));
    }
}

1 个答案:

答案 0 :(得分:9)

您没有看到问题,因为您使用的是相当旧的PHPUnit版本。当前版本为3.6.5,如果可以,您应该升级。

PHPUnit&gt;当字符串包含不可打印的字符时,3.6将显示不同的差异。就像这里的情况一样。

这是使用更新版本的输出。关于失败原因的解释如下:

phpunit
PHPUnit 3.6.5 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 3.25Mb

There was 1 failure:

1) MyTest::test_print_r
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'O:7:"MyClass":2:{s:13:"MyClassvar3";N;s:4:"var1";N;}'
+Binary String: 0x4f3a373a224d79436c617373223a323a7b733a31333a22004d79436c6173730076617233223b4e3b733a343a2276617231223b4e3b7d

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

解释

序列化的php字符串包含NULL BYTES来表示私有和受保护的类变量。

字符串"MyClassvar3"实际上是"\0MyClass\0var3"

修复断言:

$this->assertEquals(
    "O:7:\"MyClass\":2:{s:13:\"\x00MyClass\x00var3\";N;s:4:\"var1\";N;}",
    serialize($m)
);

使用它将导致测试工作。