How to embrace exception classes in PHPUnit

Im is aiming for very high code coverage and wants to either cover exception classes or exclude them from codecoverage reports.

Code example

class My_DataException extends Exception {} class Foo { function __construct() { throw new My_DataException('see?'); } } 

How can I get code coverage in My_DataException (in the /My/DataException.php library) or exclude a file from the code coverage report? I would prefer not to use the annotation method (@codeCoverageIgnore or something like that).

My phpunit.xml has a blacklist and a whitelist

 <filter> <blacklist> <directory suffix="Exception.php">../library/</directory> </blacklist> </filter> 

Each Exception file ends with "Exception.php", so I'm not sure why the suffix part does not work.

Additional Information:

  • It is not a question of the right amount of coverage.
  • I would prefer not to use the annotation method in every exception file
  • Each Exception file ends with "Exception.php", for example. My / Exception.php or My / DataException.php
+4
source share
2 answers

For the following code:

 class Foo { function __construct() { throw new My_DataException('see?'); } }s 

You will get a coverage code if you follow this line in tests:

 new Foo; 

For such a test, you can specify the Phpunit that you expect with annotation:

 /** * @expectedException My_DataException */ 

However, Exceptions are usually exceptions, so you do not cover them, but you can also be there for security reasons, and you still do not know how you can run them using test settings / data / parameters.

Then think and try to call them. Otherwise, it may turn out that the code is superfluous, because technically you cannot throw an exception, therefore, this is not necessary.

In cases where you know that they can happen, but you still cannot activate them (is this possible?), You can mark certain areas of your script that should be excluded from the coverage report in the source code:

 // @codeCoverageIgnoreStart throw new My_DataException('see?'); // @codeCoverageIgnoreEnd 

Use it rarely, you can remove it in the future.

+3
source

I was looking for a way to catch the actual exception files, here is how I ended up with the answer:

 <?php /** * Simple test for exception */ class Api_ExceptionTest extends PHPUnit_Framework_TestCase { /** * Test can construct the exception, then throw it. * * @expectedException Api_Exception */ public function testThrowException() { $exception = new Api_Exception(); throw $exception; } } 
-1
source

All Articles