使用 PHPUnit 进行单元测试并生成代码覆盖率报告

安装PHPUnit

使用 Composer 安装 PHPUnitphp

#查看composer的全局bin目录 将其加入系统 path 路径 方便后续直接运行安装的命令
composer global config bin-dir --absolute
#全局安装 phpunit
composer global require --dev phpunit/phpunit
#查看版本
phpunit --version

使用Composer构建你的项目

咱们将新建一个unit项目用于演示单元测试的基本工做流html

建立项目结构

mkdir unit && cd unit && mkdir app tests reports
#结构以下
./
├── app #存放业务代码
├── reports #存放覆盖率报告
└── tests #存放单元测试

使用Composer构建工程

#一路回车便可
composer init

#注册命名空间
vi composer.json
...
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Tests\\": "tests/"
        }
    }
...
#更新命名空间
composer dump-autoload

#安装 phpunit 组件库
composer require --dev phpunit/phpunit

到此咱们就完成项目框架的构建,下面开始写业务和测试用例。数据库

编写测试用例

建立文件app/Example.php 这里我为节省排版就不写注释了json

<?php
namespace App;

class Example
{
    private $msg = "hello world";

    public function getTrue()
    {
        return true;
    }

    public function getFalse()
    {
        return false;
    }

    public function setMsg($value)
    {
        $this->msg = $value;
    }

    public function getMsg()
    {
        return $this->msg;
    }
}

建立相应的测试文件tests/ExampleTest.phpbootstrap

<?php
namespace Tests;

use PHPUnit\Framework\TestCase as BaseTestCase;
use App\Example;

class ExampleTest extends BaseTestCase
{
    public function testGetTrue()
    {
        $example = new Example();
        $result = $example->getTrue();
        $this->assertTrue($result);
    }
    
    public function testGetFalse()
    {
        $example = new Example();
        $result = $example->getFalse();
        $this->assertFalse($result);
    }
    
    public function testGetMsg()
    {
        $example = new Example();
        $result = $example->getTrue();
        // $result is world not big_cat
        $this->assertEquals($result, "hello big_cat");
    }
}

执行单元测试

[root@localhost unit]# phpunit --bootstrap=vendor/autoload.php \
tests/

PHPUnit 6.5.14 by Sebastian Bergmann and contributors.

..F                                                                 3 / 3 (100%)

Time: 61 ms, Memory: 4.00MB

There was 1 failure:

1) Tests\ExampleTest::testGetMsg
Failed asserting that 'hello big_cat' matches expected true.

/opt/unit/tests/ExampleTest.php:27
/root/.config/composer/vendor/phpunit/phpunit/src/TextUI/Command.php:195
/root/.config/composer/vendor/phpunit/phpunit/src/TextUI/Command.php:148

FAILURES!
Tests: 3, Assertions: 3, Failures: 1.

这是一个很是简单的测试用例类,能够看到,执行了共3个测试用例,共3个断言,共1个失败,能够参照PHPUnit手册学习更多高级用法。bash

代码覆盖率

代码覆盖率反应的是测试用例测试对象行,函数/方法,类/特质的访问率是多少(PHP_CodeCoverage 尚不支持 Opcode覆盖率、分支覆盖率 及 路径覆盖率),虽然有不少人认为过度看重覆盖率是不对的,但咱们初入测试仍是俗气的追求一下吧。app

测试覆盖率的检测对象是咱们的业务代码,PHPUnit经过检测咱们编写的测试用例调用了哪些函数,哪些类,哪些方法,每个控制流程是否都执行了一遍来计算覆盖率。composer

PHPUnit 的覆盖率依赖 Xdebug,能够生成多种格式:框架

--coverage-clover <file>    Generate code coverage report in Clover XML format.
--coverage-crap4j <file>    Generate code coverage report in Crap4J XML format.
--coverage-html <dir>       Generate code coverage report in HTML format.
--coverage-php <file>       Export PHP_CodeCoverage object to file.
--coverage-text=<file>      Generate code coverage report in text format.
--coverage-xml <dir>        Generate code coverage report in PHPUnit XML format.

同时须要使用 --whitelist dir参数来设定咱们须要检测覆盖率的业务代码路径,下面演示一下具体操做:函数

phpunit \
--bootstrap vendor/autoload.php \
--coverage-html=reports/ \
--whitelist app/ \
tests/
#查看覆盖率报告
cd reports/ && php -S 0.0.0.0:8899

clipboard.png

clipboard.png

这样咱们就对业务代码App\Example作单元测试,而且得到咱们单元测试的代码覆盖率,如今天然是百分之百,由于个人测试用例已经访问了App\Example的全部方法,没有遗漏的,开发中则能体现出你的测试时用力对业务代码测试度的完善性。

基境共享测试数据

可能你会发现咱们在每一个测试方法中都建立了App\Example对象,在一些场景下是重复劳动,为何不能只建立一次而后供其余测试方法访问呢?这须要理解 PHPUnit 执行测试用例的工做流程。

咱们没有办法在不一样的测试方法中经过某成员属性来传递数据,由于每一个测试方法的执行都是新建一个测试类对象,而后调用相应的测试方法

即测试的执行模式并非

testObj = new ExampleTest();
testObj->testMethod1();
testObj->testMethod2();

而是

testObj1 = new ExampleTest();
testObj1->testMethod1();

testObj2 = new ExampleTest();
testObj2->testMethod2();

因此testMethod1()修改的属性状态没法传递给 testMethod2()使用。

PHPUnit则为咱们提供了全面的hook接口:

public static function setUpBeforeClass()/tearDownAfterClass()//测试类构建/解构时调用
protected function setUp()/tearDown()//测试方法执行前/后调用
protected function assertPreConditions()/assertPostConditions()//断言前/后调用

当运行测试时,每一个测试类大体就是以下的执行步骤

#测试类基境构建
setUpBeforeClass

#new一个测试类对象
#第一个测试用例
setUp
assertPreConditions
assertPostConditions
tearDown

#new一个测试类对象
#第二个测试用例
setUp
assertPreConditions
assertPostConditions
tearDown
...

#测试类基境解构
tearDownAfterClass

因此咱们能够在测试类构建时使用setUpBeforeClass建立一个 App\Example 对象做为测试类的静态成员变量(tearDownAfterClass主要用于一些资源清理,好比关闭文件,数据库链接),而后让每个测试方法用例使用它:

<?php
namespace Tests;

use App\Example;
use PHPUnit\Framework\TestCase as BaseTestCase;

class ExampleTest extends BaseTestCase
{
    // 类静态属性
    private static $example;

    public static function setUpBeforeClass()
    {
        self::$example = new Example();
    }

    public function testGetTrue()
    {
        // 类的静态属性更新
        self::$example->setMsg("hello big_cat");
        $result = self::$example->getTrue();
        $this->assertTrue($result);
    }

    public function testGetFalse()
    {
        $result = self::$example->getFalse();
        $this->assertFalse($result);
    }

    /**
     * 依赖 testGetTrue 执行完毕
     * @depends testGetTrue
     * @return [type] [description]
     */
    public function testGetMsg()
    {
        $result = self::$example->getMsg();
        $this->assertEquals($result, "hello big_cat");
    }
}

或者使用@depends注解来声明两者的执行顺序,并使用传递参数的方式来知足需求。

public function testMethod1()
{
    $this->assertTrue(true);
    return "hello";
}

/**
 * @depends testMethod1
 */
public function testMethod2($str)
{
    $this->assertEquals("hello", $str);
}
#执行模式大概以下
testObj1 = new Test;
$str = testObj1->testMethod1();

testObj2 = new Test;
testObj2->testMethod2($str);

理解测试执行的模式仍是颇有帮助的,其余高级特性请浏览官方文档

使用phpunit.xml编排测试套件

使用测试套件来管理测试,vi phpunit.xml

<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="./vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <!--能够定义多个 suffix 用于指定待执行的测试类文件后缀-->
        <testsuite name="Tests">
            <directory suffix="Test.php">./test</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <!--能够定义多个 对./app下的业务代码作覆盖率统计-->
            <directory suffix=".php">./app</directory>
        </whitelist>
    </filter>
    <logging>
        <!--覆盖率报告生成类型和输出目录 lowUpperBound低覆盖率阈值 highLowerBound高覆盖率阈值-->
        <log type="coverage-html" target="./reports" lowUpperBound="35" highLowerBound="70"/>
    </logging>
</phpunit>

而后直接运phpunit行便可:

[root@localhost unit]# phpunit 
PHPUnit 6.5.14 by Sebastian Bergmann and contributors.

Time: 81 ms, Memory: 4.00MB

No tests executed!

Generating code coverage report in HTML format ... done
相关文章
相关标签/搜索