Make phpunit catch php7 TypeError

Try this:

$this->expectException(TypeError::class);

Yes, you can test for TypeError the same way you would use for any other exception.

However, I would not test that PHP emits a type error in case of a type mismatch. This is the kind of test that becomes superfluous with PHP 7 code.


Sadly, TypeError is not a subclass of Exception (reference), whilst it extends Error. The only thing they are really sharing is the the Throwable interface. The ThrowMatcher can't actually catch a TypeError.

If you look at the code in src/PhpSpec/Matcher/ThrowMatcher.php, you can see that PHPSpec catches Exceptions that inherit 'Exception' and then checks the instance type of that exception.

See also this answer.

Tags:

Phpunit

Php 7