Last Updated: February 25, 2016
·
12.09K
· x3ro

Catch PHP warnings and notices when unit testing

PHP is great at not telling you if you do something wrong, and that usually comes back to bite you. This holds even when writing proper unit tests, because warnings and notices are separete from the exception mechanism in PHP, and so at least PHPUnit wont catch them.

But another PHP rule holds here too: there's usually a hack-ish workaround :) Just use a custom error handler such as the following, which throws exceptions for notices, warnings and other "non-exceptional" errors in PHP:

public function setUp() {
    set_error_handler(function($errno, $errstr, $errfile, $errline) {
        throw new RuntimeException($errstr . " on line " . $errline . " in file " . $errfile);
    });
}

public function tearDown() {
    restore_error_handler();
}

And thats it, for PHPUnit:

Of course your unit testing framework must support setUp and tearDown methods, and you might need to modify the snippet to work with your setup.

Happy testing!

3 Responses
Add your response

That's so tiny and elegant! Thanks for the tip.

over 1 year ago ·

You can use also a more elegant way. You can tell php unit at the phpunit.xml to convert errors to exceptions.

... convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" ... </code>

read here http://phpunit.de/manual/3.7/en/appendixes.configuration.html

over 1 year ago ·

Thanks @gjerokrsteski :) I suspected that there might be an option for this, but I couldn't find it at the time. Nonetheless, it does not fit my usecase, because I need to be able to selectively enable this functionality for certain tests/test suites. But very good to know!

over 1 year ago ·