fix for toString error in PHPUnit

I was struggling to get PHPUnit to run under PHP 5.2.9. I’ve only used PHPUnit a little, so may have simply got something wrong, but I kept getting the error:

Catchable fatal error: Object of class AbcTest could not be converted to string in {dir}/PHPUnit/Framework/TestFailure.php on line 98

The error happens in the PHPUnit_Framework_TestFailure::toString method, which tries to implicitly convert a test case to a string.

The class AbcTest is my test case, which it is trying to display following a test failure.  PHPUnit test cases all extend PHPUnit_Framework_TestCase and while this has a toString method it does not have the ‘magic method__toString required by PHP 5.2 onwards.

To fix the problem I simply added the following method to the class PHPUnit_Framework_TestCase in PHPUnit/Framework/TestCase.php .

public function __toString()
 {
 return $this->toString();
 }

I am using PHPUnit 3.4.9, but peeking at 3.5.0beta it looks the same.  I’m guessing the PHPUnit_Framework_TestFailure::toString method is not used much so has got missed since the change to PHP 5.2.x.

PHPUnit is now in GITHub so I really ought to work out how to submit corrections to that … but another day I think.

3 thoughts on “fix for toString error in PHPUnit

  1. Bravo!!! Thx!!
    Next function placed in the class from which the error occurs can also be used

    function __toString()
    {
    return ”;
    }

  2. that would fix the error, in that it would not give a runtime error, but not giver what the writer of the code that used it meant it to do.

    Arguably my fix ‘covers up’ the error and in other cases I might include something that is informative, but also makes the fact that an error occurred more obvious, either logging the fact that the function had been called or highlighting the fact in the return value.

    return “** missing __toString **: ” . $this->toString();

    However, in this case it was effectively someone else’s code (in the PHPUnit test framework itself), so I wanted the error to go away entirely.

  3. How can I fix this error.
    PHP Fatal error: Call to undefined method PHP_CodeCoverage_Filter::getInstance() in /usr/bin/phpunit on line 39

Comments are closed.