Search code examples
phpunit-testingphpunitassertassertions

How to handle a failed PHP assertion with PHPUnit?


I have an assertion in my code. Something like:

assert('is_string($var)');

If I write a test for PHPUnit that causes this assertion to fail with the message, Warning: assert(): Assertion "is_string($var)" failed in /path/to/file.php on line ###

And, my test also fails. I've tried adding @expectedException PHPUnit_Framework_Error_Warning to the docblock according to the documentation, but that doesn't help. What do I need to do to make my test expect that this assertion will fail?


Solution

  • From php.net/assert:

    Assertions should be used as a debugging feature only. You may use them for sanity-checks that test for conditions that should always be TRUE and that indicate some programming errors if not or to check for the presence of certain features like extension functions or certain system limits and features.

    Assertions should not be used for normal runtime operations like input parameter checks. As a rule of thumb your code should always be able to work correctly if assertion checking is not activated.

    So for normal code logic, use a boolean or some pre-defined constants. For exceptional logic use normal if statements and throw an Exception for invalid input.

    If you are really keen on keeping the asserts, you could define an assert callback which throws an Exception you can catch in PHPUnit.

    // PHP 5.3 Anonymous function as callback
    // code is untested
    assert_options(ASSERT_CALLBACK, function($file, $line, $code) {
        throw new Exception('Assert failed in $file on line $line');
    });