How to exclude files / code blocks from code cover

2019-03-18 04:15发布

问题:

Requirements:

  • Netbeans with PHPUnit(6.9)
  • EDIT: Same applies, for example, to PHPStorm

How to:

  • Exclude lines from code coverage.
  • Exclude code blocks (lines) from code coverage.

回答1:

If you are trying to achieve 100% code coverage but have one or more lines that you cannot test, you can surround them with special annotations. They will be ignored in the code coverage report.

if (($result = file_get_contenst($url)) === false) {
    // @codeCoverageIgnoreStart
    $this->handleError($url);
    // @codeCoverageIgnoreEnd
}

Edit: I have found that Xdebug often considers the closing brace to be executable. :( If that happens, move the end tag below it.



回答2:

To ignore method code blocks:

/**
 * @codeCoverageIgnore
 */
function functionToBeIgnored() {
    // function implementation
}

To ignore class code blocks:

/**
 * @codeCoverageIgnore
 */
class Foo {
    // class implementation
}

And as @david-harkness said, to ignore individual lines:

// @codeCoverageIgnoreStart
print 'this line ignored for code coverage';
// @codeCoverageIgnoreEnd

More information can by found in the PHPUnit Documentation under the Ignoring code blocks heading.



回答3:

First make sure you have the latest and greatest phpunit or else the code ignore might be missing. Next create a phpunit.xml file that looks something like this:

<phpunit colors="true">
    <filter>
        <blacklist>
            <file>file1.php</file>
            <file>file2.php</file>
        </blacklist>
    </filter>
</phpunit>