Does anyone know whether there is an assert
or something like that which can test whether an exception was thrown in the code being tested?
Does anyone know whether there is an assert
or something like that which can test whether an exception was thrown in the code being tested?
An alternative way can be the following:
Please ensure that your test class extents
\PHPUnit_Framework_TestCase
.Code below will test exception message and exception code.
Important: It will fail if expected exception not thrown too.
If you're running on PHP 5.5+, you can use
::class
resolution to obtain the name of the class withexpectException
/setExpectedException
. This provides several benefits:string
so it will work with any version of PHPUnit.Example:
PHP compiles
into
without PHPUnit being the wiser.
Be very carefull about
"/**"
, notice the double "*". Writing only "**"(asterix) will fail your code. Also make sure your using last version of phpUnit. In some earlier versions of phpunit @expectedException Exception is not supported. I had 4.0 and it didn't work for me, I had to update to 5.5 https://coderwall.com/p/mklvdw/install-phpunit-with-composer to update with composer.Comprehensive Solution
PHPUnit's current "best practices" for exception testing seem.. lackluster (docs).
Since I strongly disagree with the current
expectException
implementation, I made a trait to use on my test cases. It's only 50 lines.assert
syntaxassertNotThrows
Library
I published the
AssertThrows
trait to Github and packagist so it can be installed with composer.Simple Example
Just to illustrate the spirit behind the syntax:
Pretty neat?
Full Usage Example
Please see below for a more comprehensive usage example:
The PHPUnit
expectException
method is very inconvenient because it allows to test only one exception per a test method.I've made this helper function to assert that some function throws an exception:
Add it to your test class and call this way: