Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WHy does PHPUnit give me an assertEquals failure for apparently identical strings?

Tags:

php

phpunit

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)));
    }
}
like image 553
Peter Avatar asked Jan 19 '23 00:01

Peter


1 Answers

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:

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

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:

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

Using this will result in the test working.


like image 75
edorian Avatar answered Jan 29 '23 12:01

edorian