我最近开始在PHPUnit中使用strict
模式,但在测试代码覆盖率时遇到了一个问题:
如果我使用setUp
方法来创建我的类的新实例,则在运行测试时__constructor
方法会被列入代码覆盖范围。
这是我的测试设置:
phpunit.config.xml
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.5/phpunit.xsd"
bootstrap="../vendor/autoload.php"
backupGlobals="false"
backupStaticAttributes="false"
colors="true"
verbose="true"
beStrictAboutOutputDuringTests="true"
beStrictAboutTestSize="true"
beStrictAboutTestsThatDoNotTestAnything="true"
beStrictAboutTodoAnnotatedTests="true"
checkForUnintentionallyCoveredCode="true"
processIsolation="false"
>
<testsuites>
<testsuite name="FooTests">
<directory suffix="Test.php">../tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">../src</directory>
</whitelist>
</filter>
<logging>
<log type="coverage-html" target="coverage/" higlight="true" showUncoveredFiles="true"></log>
</logging>
Foo.php
class Foo
{
protected $_bar;
public function __construct($bar)
{
$this->_bar=$bar; //Line 10
} //Line 11
public function getBar()
{
return $this->_bar;
}
public function getBar2()
{
return $this->_bar;
}
}
以及测试: FooTest.php
class FooTest extends \PHPUnit_Framework_TestCase
{
protected $_foo;
protected function setUp()
{
$this->_foo=new Foo(10);
}
public function testGetBar()
{
$this->assertSame(10, $this->_foo->getBar());
}
/**
* @covers Foo::getBar2
*/
public function testGetBar2()
{
$this->assertSame(10, $this->_foo->getBar2());
}
}
如果我运行测试,我会得到这个结果:
PHPUnit 4.5.0 by Sebastian Bergmann and contributors.
Configuration read from C:\xampp\htdocs\unittest\build\phpunit.config.xml
.R
Time: 88 ms, Memory: 3.50Mb
There was 1 risky test:
1) FooTest::testGetBar2
This test executed code that is not listed as code to be covered or used:
- C:\xampp\htdocs\unittest\src\Foo.php:10
- C:\xampp\htdocs\unittest\src\Foo.php:11
OK, but incomplete, skipped, or risky tests!
Tests: 2, Assertions: 2, Risky: 1.
Generating code coverage report in HTML format ... done
一旦我在测试中指定了@covers
,问题就出现了。
这是预期行为吗?
我尝试过以下一些方法:
- 将
checkForUnintentionallyCoveredCode
更改为false
,显然可以解决问题,但我想使用此功能…… - 使用
processIsolation="true"
也可以解决问题。但我不知道为什么? - 将
@covers
或@uses
添加到setUp()
中不起作用 - 将
@covers
添加到setUp()
使用的测试中确实有效,但测试实际上并没有覆盖代码。(如果测试变得更加复杂,写起来可能很麻烦...) - 不同的
phpunit
版本:我尝试了4.3
和4.5
,结果相同 - 不同的PHP设置:我在Win8上使用XAMPP和LinuxMint上尝试过,结果相同
是否有办法从代码覆盖率中删除setUp()
代码,并在测试实际测试的方法上使用@covers
?
编辑:这也影响继承。所以如果Bar
继承自Foo
,并将参数传递给Foo::__construct
,那么代码覆盖率也会包含这部分-这使得编写__construct
的@covers
很麻烦…
附加信息:
PHP 5.6.3 (cli) (built: Nov 12 2014 17:18:08)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2014 Zend Technologies
with Xdebug v2.2.5, Copyright (c) 2002-2014, by Derick Rethans