11 代码覆盖率
环境搭建
- 安装PHP_CodeCoverage拓展
- 安装XDebug
PHPUnit支持的代码覆盖率衡量标准
- 行覆盖率
- 函数与方法覆盖率
- 类与
trait
类的覆盖率
设置监测白名单
- 命令行中使用:
--whitelist
来设置 - 或者修改XML配置文件
忽略代码块
@codeCoverageIgnore
@codeCoverageIgnoreStart
@codeCoverageIgnoreEnd
<?php
use PHPUnit\Framework\TestCase;
/**
* @codeCoverageIgnore
*/
class Foo
{
public function bar()
{
}
}
class Bar
{
/**
* @codeCoverageIgnore
*/
public function foo()
{
}
}
if (false) {
// @codeCoverageIgnoreStart
print '*';
// @codeCoverageIgnoreEnd
}
exit; // @codeCoverageIgnore
?>
代码中被忽略掉的行(用标注标记为忽略)将会计为已执行(如果它们是可执行的),并且不会在代码覆盖情况中被高亮标记。
指明要覆盖的方法
@covers
标注可以用在测试代码中来指明测试方法想要对哪些方法进行测试。如果提供了这个信息,则只有指定方法的代码覆盖率信息会被统计。
请和前面几章中的有风险的测试相关联。
<?php
use PHPUnit\Framework\TestCase;
class BankAccountTest extends TestCase
{
protected $ba;
protected function setUp()
{
$this->ba = new BankAccount;
}
/**
* @covers BankAccount::getBalance
*/
public function testBalanceIsInitiallyZero()
{
$this->assertEquals(0, $this->ba->getBalance());
}
/**
* @covers BankAccount::withdrawMoney
*/
public function testBalanceCannotBecomeNegative()
{
try {
$this->ba->withdrawMoney(1);
}
catch (BankAccountException $e) {
$this->assertEquals(0, $this->ba->getBalance());
return;
}
$this->fail();
}
/**
* @covers BankAccount::depositMoney
*/
public function testBalanceCannotBecomeNegative2()
{
try {
$this->ba->depositMoney(-1);
}
catch (BankAccountException $e) {
$this->assertEquals(0, $this->ba->getBalance());
return;
}
$this->fail();
}
/**
* @covers BankAccount::getBalance
* @covers BankAccount::depositMoney
* @covers BankAccount::withdrawMoney
*/
public function testDepositWithdrawMoney()
{
$this->assertEquals(0, $this->ba->getBalance());
$this->ba->depositMoney(1);
$this->assertEquals(1, $this->ba->getBalance());
$this->ba->withdrawMoney(1);
$this->assertEquals(0, $this->ba->getBalance());
}
}
?>
同时,可以用
@coversNothing
标注来指明一个测试不覆盖任何方法。这可以在编写集成测试时用于确保代码覆盖全部来自单元测试。
<?php
use PHPUnit\Framework\TestCase;
class GuestbookIntegrationTest extends PHPUnit_Extensions_Database_TestCase
{
/**
* @coversNothing
*/
public function testAddEntry()
{
$guestbook = new Guestbook();
$guestbook->addEntry("suzy", "Hello world!");
$queryTable = $this->getConnection()->createQueryTable(
'guestbook', 'SELECT * FROM guestbook'
);
$expectedTable = $this->createFlatXmlDataSet("expectedBook.xml")
->getTable("guestbook");
$this->assertTablesEqual($expectedTable, $queryTable);
}
}
?>