什么是代码覆盖率?你如何衡量它?
有人问我这个关于自动化测试代码覆盖率的问题。似乎在自动化工具之外,它更像是艺术而不是科学。是否有任何关于如何使用代码覆盖的实际示例?
什么是代码覆盖率?你如何衡量它?
有人问我这个关于自动化测试代码覆盖率的问题。似乎在自动化工具之外,它更像是艺术而不是科学。是否有任何关于如何使用代码覆盖的实际示例?
当前回答
在前面的回答中,已经很好地解释了代码覆盖率。我只是补充了一些与工具相关的知识,如果你在iOS和OSX平台上工作,Xcode提供了测试和监控代码覆盖率的工具。
参考链接:
https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/testing_with_xcode/chapters/07-code_coverage.html
https://medium.com/zendesk-engineering/code-coverage-and-xcode-6b2fb8756a51
两者都是学习和探索Xcode代码覆盖率的有用链接。
其他回答
在前面的回答中,已经很好地解释了代码覆盖率。我只是补充了一些与工具相关的知识,如果你在iOS和OSX平台上工作,Xcode提供了测试和监控代码覆盖率的工具。
参考链接:
https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/testing_with_xcode/chapters/07-code_coverage.html
https://medium.com/zendesk-engineering/code-coverage-and-xcode-6b2fb8756a51
两者都是学习和探索Xcode代码覆盖率的有用链接。
代码覆盖率测试的目的是找出有多少代码被测试。代码覆盖工具生成一个报告,其中显示了多少应用程序代码已经运行。代码覆盖率以百分比来衡量,越接近100%越好。这是一个白盒测试的例子。下面是一些用于代码覆盖率测试的开源工具:
Simplecov -用于Ruby Coverlet -用于。net Cobertura -用于Java cover .py -用于Python Jest -用于JavaScript
代码覆盖率只是对所测试代码的度量。有多种可以度量的覆盖标准,但通常是程序中的各种路径、条件、函数和语句构成了总覆盖。代码覆盖率度量是执行每种覆盖率标准的测试的百分比。
至于我如何跟踪项目中的单元测试覆盖率,我使用静态代码分析工具来跟踪。
对之前的许多答案进行了几点补充:
代码覆盖率意味着您的测试集覆盖源代码的程度。也就是说,源代码在多大程度上被测试用例集所覆盖。
正如在上面的回答中提到的,有各种各样的覆盖标准,比如路径、条件、函数、语句等。但要涵盖的其他标准是
Condition coverage: All boolean expressions to be evaluated for true and false. Decision coverage: Not just boolean expressions to be evaluated for true and false once, but to cover all subsequent if-elseif-else body. Loop Coverage: means, has every possible loop been executed one time, more than once and zero time. Also, if we have assumption on max limit, then, if feasible, test maximum limit times and, one more than maximum limit times. Entry and Exit Coverage: Test for all possible call and its return value. Parameter Value Coverage (PVC). To check if all possible values for a parameter are tested. For example, a string could be any of these commonly: a) null, b) empty, c) whitespace (space, tabs, new line), d) valid string, e) invalid string, f) single-byte string, g) double-byte string. Failure to test each possible parameter value may leave a bug. Testing only one of these could result in 100% code coverage as each line is covered, but as only one of seven options are tested, means, only 14.2% coverage of parameter value. Inheritance Coverage: In case of object oriented source, when returning a derived object referred by base class, coverage to evaluate, if sibling object is returned, should be tested.
注意:静态代码分析将发现是否有任何不可访问的代码或挂起的代码,即没有被任何其他函数调用覆盖的代码。还有其他静态报道。即使静态代码分析报告100%的代码被覆盖了,如果所有可能的代码覆盖率都被测试了,它也不会给出关于您的测试集的报告。
对于PHP,你应该看看Sebastian Bergmann的Github
提供PHP代码覆盖率信息的收集、处理和呈现功能。
https://github.com/sebastianbergmann/php-code-coverage