dpkajqd31574096 2013-09-16 06:25
浏览 45

有没有办法让PHPUnit确定@method声明的代码覆盖率?

I have a number of methods being declared in a class with the standard phpdoc @method syntax, for example:

/**
 * @method string magicMethod(int $arg1, array $arg2) Method description.
 */
class ... { }

Is it possible to configure PHPUnit to check against these comments when determining method-level code coverage? Currently, my coverage is at 100%, even though I've only touched about 10% of these magic methods so far.

  • 写回答

3条回答 默认 最新

  • dousi5501 2013-09-16 22:49
    关注

    Code coverage can only be calculated based on existing code, not on "virtual" methods.

    To get a more realistic statistic, you should reduce the amount of coverage that gets generated unintentionally. PHPUnit does generate coverage for every line of code that gets executed when using the default configuration - which is bad, because if you unintentionally run along lines that do not get tested with an assertion, the coverage does not tell you anything at all (apart from the fact that no error occurred there).

    When you have a look at the code coverage chapter in the manual, you see that you can specify which methods are tested with a test, and only those methods are generating coverage statistics (section "Specifying covered methods").

    The method I prefer is to set the option mapTestClassNameToCoveredClassName="true" in the phpunit.xml file, and add all classes to be tested to the whitelist. That way, the coverage will automatically be restricted to only the class that has the same name (less the suffix "Test") as the test class. So if you have a test "MyGreatModelTest", it will only create coverage in any method of the "MyGreatModel" class, and not anywhere else.

    And if you add the whole directory with your code to the whitelist, you will also catch all files that did generate 0 % coverage and thus were not included in the statistics so far.

    Beware: These settings might hurt your feelings, but they will give you a more realistic picture of which lines of code get really run during a test, and which are only passed as a side effect.

    评论

报告相同问题?