php覆盖率之phpunit生成覆盖率

一. 安装phpunit

参照phpunit中文网安装:http://www.phpunit.cn/manual/current/zh_cn/installation.html

$ wget https://phar.phpunit.de/phpunit.phar$ chmod +x phpunit.phar$ sudo mv phpunit.phar /usr/local/bin/phpunit$ phpunit --version
本地mac也能安装成功,按照步骤安装后,phpunit --version的输出信息如下:


从提示信息看,本地的php版本是5.6.30,PHPunit支持的版本是php7.0 or php7.1,所以需要更新phpunit的版本:

$ wget https://phar.phpunit.de/phpunit-5.6.3.phar

$ chmod +x phpunit.phar

$ sudo mv phpunit.phar /usr/local/bin/phpunit

$phpunit --version


二. 生成覆盖率

1.假设测试的类为./src/BankAccount.php:

<?php

    class BankAccount {

        protected $balance = 0;

        public function getBalance() {

            return $this->balance;

        }

        public function setBalance($balance) {

            if ($balance >= 0) {

                $this->balance = $balance;

            } else {

                throw new BankAccountException;

            }

        }

    }

?>


2. 单测文件内容./test/BankAccountTest.php:

<?php

    require_once './src/BankAccount.php';

    class BankAccountTest extends PHPUnit_Framework_TestCase {

        protected $ba;

        protected function setUp() {

            $this->ba = new BankAccount;

        }

        public function testBalanceIsInitiallyZero() {

            $this->assertEquals(0, $this->ba->getBalance());

        }

    }

?>


3. 执行命令生成覆盖率

$ phpunit --coverage-html ./report BankAccountTest.php

此时会提示错误:

Error:         No code coverage driver is available

因为本地php版本为5.6,所以使用brew命令安装php56-xdebug:

brew install homebrew/php/php56-xdebug

安装完成后,提示错误:

No whitelist configured, no code coverage will be generated

此时需要配置phpunit.xml,配置内容如下:

 <?xml version="1.0" encoding="UTF-8"?>

<phpunit colors="true">

    <testsuites>

        <testsuite name="Application Test Suite">

            <directory suffix=".php">./src</directory><!--存放ut文件的目录-->

        </testsuite>

    </testsuites>

    <filter>

      <whitelist processUncoveredFilesFromWhitelist="true">

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

      </whitelist>

    </filter>

</phpunit>

phpunit.xml放在刚才新建的代码目录下,重新执行:

$ phpunit --coverage-html ./report BankAccountTest.php

此时会在当前目录下生成一个report目录,目录下就是单测覆盖率统计数据。


4.效果展示