Search code examples
phpunitcode-coveragexdebug

Hide private + protected methods from code coverage report?


Can I hide private & protected methods from PhpUnit's code coverage report?

I know some other people are suggesting that one should test them "indirectly" but I really don't care if they get called or not and I think it's an utter waste of time for me to set up @covers for private utility methods.

Here's my phpunit.xml if you need to see that:

<phpunit
        backupGlobals="false"
        backupStaticAttributes="false"
        bootstrap="vendor/autoload.php"
        colors="true"
        convertErrorsToExceptions="true"
        convertNoticesToExceptions="true"
        convertWarningsToExceptions="true"
        processIsolation="false"
        stopOnFailure="false"
        syntaxCheck="false"
        timeoutForSmallTests="1"
        timeoutForMediumTests="10"
        timeoutForLargeTests="60">

    <testsuites>
        <testsuite name="default">
            <directory>./tests</directory>
            <exclude>
                <directory suffix=".php">./src/Internal</directory>
            </exclude>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory suffix=".php">./src</directory>
        </whitelist>
    </filter>

    <logging>
        <log type="coverage-html" target="./log/codeCoverage" charset="UTF-8" yui="true" highlight="true" lowUpperBound="50" highLowerBound="80"/>
        <log type="testdox-html" target="./log/testdox.html"/>
    </logging>
</phpunit>

code coverage


Solution

  • Well, as far as I know, it's not a PHPUnit functionality and you must fork php-code-coverage project and edit the source code. Probably that's not the answer you are looking for but it seems this is the only option right now.

    It is comforting that the changes are pretty simple. You might edit CodeCoverage::getLinesToBeIgnored method and add extra condition

    if (get_class($token) == 'PHP_Token_FUNCTION') {
        $methodVisibility = $token->getVisibility();
    
        if ($methodVisibility == 'private' || $methodVisibility == 'protected') {
           $endLine = $token->getEndLine();
    
           for ($i = $token->getLine(); $i <= $endLine; $i++) {
               self::$ignoredLines[$filename][$i] = TRUE;
           }
        }
    }
    

    enter image description here Method getSomething is ignored without using @codeCoverageIgnore or any other doc blocks.