Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit code coverage for "require_once" statements

Can I exclude "require_once" statements from code coverage? The lines with "require_once" are reported as not covered but it is not possible if other lines in the script are covered:

enter image description here

PHP 7.0.11, PHPUnit 5.5.7 & XDebug 2.4.0 are used for code coverage.

like image 846
Alex Gusev Avatar asked Nov 03 '25 12:11

Alex Gusev


2 Answers

In the PHPUnit documentation there is mentioning of excluding code blocks from coverage using @codeCoverageIgnoreStart / @codeCoverageIgnoreEnd / @codeCoverageIgnore comments.

So you can try something like:

// @codeCoverageIgnoreStart
require_once __DIR__ . '/Data/TData.php';
require_once __DIR__ . '/Data/Path.php';
// @codeCoverageIgnoreEnd

or

require_once __DIR__ . '/Data/TData.php'; // @codeCoverageIgnore
require_once __DIR__ . '/Data/Path.php'; // @codeCoverageIgnore
like image 80
BVengerov Avatar answered Nov 06 '25 02:11

BVengerov


You have forceCoversAnnotation enabled.

forceCoversAnnotation

Code Coverage will only be recorded for tests that use the @covers annotation documented in the section called "@covers".

— Appendix C. The XML Configuration File

Disabling forceCoversAnnotation will produce coverage of the require_once calls.

For example, you can disable forceCoversAnnotation in the phpunit.xml configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit forceCoversAnnotation="false">
...

If you want to use @covers annotations then you will either need to disable checkForUnintentionallyCoveredCode or wrap the require_once calls in @codeCoverageIgnore* annotations.

Either

<?xml version="1.0" encoding="UTF-8"?>
<phpunit forceCoversAnnotation="true"
         checkForUnintentionallyCoveredCode="false">
...

Or

// @codeCoverageIgnoreStart
require_once __DIR__ . '/Data/TData.php';
require_once __DIR__ . '/Data/Path.php';
// @codeCoverageIgnoreEnd

The reason, is that using forceCoversAnnotation means you want to specify everything that is covered explicitly. You do this by using the @covers annotations. The @uses annotation let's you specify code that is intentionally covered by a test. But @uses can't be used to specify code that causes side-effects e.g. require_once statements. This is where @codeCoverageIgnoreStart and @codeCoverageIgnoreEnd comes in, it allows you to explicitly specify code that coverage should ignore.

Most of these annotations are about strictness of code coverage.

like image 39
Gerard Roche Avatar answered Nov 06 '25 02:11

Gerard Roche