47

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.
tivnet
  • 1,898
  • 17
  • 19
Alfred
  • 60,935
  • 33
  • 147
  • 186

3 Answers3

84

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.

bnp887
  • 5,128
  • 2
  • 26
  • 30
51

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_contents($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.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
David Harkness
  • 35,992
  • 10
  • 112
  • 134
  • I had an old version of PHPUnit so that code did not work. I figured it out but thanks. Even a better solution is to use phpunit.xml => I post answer.. – Alfred Feb 07 '11 at 02:15
  • Confirmed with PHPStorm: need to move the end tag after the closing bracket. – tivnet Jun 04 '15 at 19:40
  • Only problem with this is that the actual classes have ugly codecoverageignore blocks in them which I dont like –  May 12 '20 at 18:44
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>
Alfred
  • 60,935
  • 33
  • 147
  • 186
  • 6
    Your question asked about excluding lines and blocks which the above will not do--it ignores entire files. Also, if you use a whitelist (my company does), the blacklist is ignored. – David Harkness Feb 08 '11 at 03:11
  • Oops thanks David. This question was asked so long ago and in the title it says file. But thanks for the information. – Alfred Feb 08 '11 at 13:30