Why is PHPUnit giving me an assertEquals error for explicitly identical strings?

The following script demonstrates and documents (in the header comment) the problem, namely, that I cannot detect the difference between the “expected” and “actual” lines:

<?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))); } } 
+4
source share
1 answer

You do not see the problem because you are using a rather old version of PHPUnit. The current version is 3.6.5 , and if you can upgrade it.

PHPUnit> 3.6 will be different from you when the string contains non-printable characters. As is the case here.

Here is the result using a more current version. An explanation of the reasons for the failure is below:

 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. 

Explanation

The serialized php string contains NULL BYTES to denote private and protected class variables.

The string "MyClassvar3" really "\0MyClass\0var3" .

To correct the statement:

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

Using this will make the test work.


+9
source

Source: https://habr.com/ru/post/1386982/


All Articles