为什么对于明显相同的字符串,PHPUnit 会给我一个assertEquals 失败?
以下脚本既演示并记录了问题(在标题注释中),即我无法检测“预期”和“实际”字符串之间的任何差异:
<?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)));
}
}
The following script both demonstrates and documents (in the header comment) the issue, namely that I am unable to detect any difference between the "expected" and "actual" strings:
<?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)));
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您没有看到问题,因为您使用的是相当旧的 PHPUnit 版本。当前版本是
3.6.5
,如果可以的话,您应该升级。PHPUnit>>当字符串包含不可打印字符时,3.6 将向您显示不同的差异。就像这里的情况一样。
这是使用更新版本的输出。失败原因的解释如下:
解释
序列化的 php 字符串包含 NULL BYTES 来表示私有和受保护的类变量。
字符串
"MyClassvar3"
实际上是"\0MyClass\0var3"
。修复断言:
使用此断言将导致测试正常工作。
You don't see the Problem because you are using a quite old PHPUnit Version. The current version is
3.6.5
and if you can you should upgrade.PHPUnit > 3.6 will show a differnt diff to you when the string contains unprintable characters. As is the case here.
Here is the output using a more current Version. The explanation on why it fails is below:
Explanation
A serialized php string contains
NULL BYTES
to denote private and protected class variables.The string
"MyClassvar3"
is really"\0MyClass\0var3"
.To fix the assertion:
Using this will result in the test working.