安装 PHPUnit 与构建项目
安装 PHPUnit
借助 Composer 工具来安装 PHPUnit
#查看composer的全局bin目录 将其加入系统 path 路径 方便后续直接运行安装的命令
composer global config bin-dir --absolute
#全局安装 phpunit
composer global require --dev phpunit/phpunit
#查看版本
phpunit --version
利用 Composer 来搭建项目环境
接下来将创建一个名为 unit 的项目实例,以此展示单元测试的标准操作流程
设计项目的目录结构
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,为保持篇幅简洁此处省略注释部分
<?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;
}
}</code></pre>
建立对应的测试文件 <code>tests/ExampleTest.php</code>
<pre class="brush:php;"><code class="language-php">
<?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");
}
}</code></pre>
运行单元测试
<pre class="brush:bash;"><code class="language-bash">
[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.</code></pre>
这是一个极简的测试类示例,执行结果显示共运行 3 个测试用例,包含 3 个断言,其中 1 个失败,更多高级用法可参考 <code>PHPUnit</code> 官方手册
<h2>生成代码覆盖率报告</h2>代码覆盖率分析
代码覆盖率衡量的是 <code>测试用例</code> 对 <code>测试对象</code> 中 <code>行,函数/方法,类/特质</code> 的访问比例(注:<code>PHP_CodeCoverage</code> 目前暂不支持 <code>Opcode覆盖率、分支覆盖率 及 路径覆盖率</code>)。尽管业界普遍认为过度追求覆盖率并非最佳实践,但对于初学者而言,适度关注覆盖率仍是必要的
覆盖率检测的目标是业务代码,PHPUnit 通过追踪测试用例调用的函数、类、方法以及控制流的执行情况来计算覆盖率数值
<code>PHPUnit</code> 的覆盖率功能依赖于 <code>Xdebug</code>,支持生成多种格式的报表:
<pre class="brush:plain;"><code class="language-plain">
--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.</code></pre>
同时需配合 <code>--whitelist dir</code> 参数指定需要检测的业务代码路径,具体操作演示如下
<pre class="brush:php;"><code class="language-php">
phpunit \
--bootstrap vendor/autoload.php \
--coverage-html=reports/ \
--whitelist app/ \
tests/
#查看覆盖率报告
cd reports/ && php -S 0.0.0.0:8899</code></pre>
<img title="clipboard.png" alt="" src="/uploads/20261125/b188b0f484eef19c21f592fcef1fc5d73512a28136d9bb929b909b92d86c11cf.png" />
<img title="clipboard.png" alt="" src="/uploads/20261125/3b23cc9d60c4ca04fd46c2f5d4817537cd3e5da94cc828c30b8b9a43bd5234df.png" />
这样便完成了对业务代码 <code>App\Example</code> 的单元测试,并获取了相应的代码覆盖率数据。当前结果为百分之百,因为测试用例已完整访问了 <code>App\Example</code> 的所有方法,无遗漏情况;在实际开发中,这能直观反映测试工作的完备性
<h2>处理测试基境数据共享</h2>基境共享测试数据
可能会发现每个测试方法中都重复创建了 <code>App\Example</code> 对象,造成冗余劳动。若能仅创建一次供其他方法复用则更为高效,这需要理解 PHPUnit 的执行机制
无法在 <code>不同的测试方法</code> 之间通过 <code>某成员属性</code> 传递数据,因为每个 <code>测试方法</code> 的执行都是独立 <code>新建</code> 一个 <code>测试类对象</code>,随后调用相应的 <code>测试方法</code>
即测试的执行模式并非连续对象复用
<pre class="brush:php;"><code class="language-php">
testObj = new ExampleTest();
testObj->testMethod1();
testObj->testMethod2();</code></pre>
而是每次测试都创建新实例
<pre class="brush:php;"><code class="language-php">
testObj1 = new ExampleTest();
testObj1->testMethod1();
testObj2 = new ExampleTest();
testObj2->testMethod2();</code></pre>
因此 <code>testMethod1()</code> 修改的 <code>属性状态</code> 状态无法传递给 <code>testMethod2()</code> 使用
<code>PHPUnit</code> 提供了全面的 <code>hook</code> 接口来解决此问题:
<pre class="brush:php;"><code class="language-php">
public static function setUpBeforeClass()/tearDownAfterClass()//测试类构建/解构时调用
protected function setUp()/tearDown()//测试方法执行前/后调用
protected function assertPreConditions()/assertPostConditions()//断言前/后调用</code></pre>
当运行测试时,每个测试类的执行步骤大致如下
<pre class="brush:php;"><code class="language-php">
#测试类基境构建
setUpBeforeClass
#new一个测试类对象
#第一个测试用例
setUp
assertPreConditions
assertPostConditions
tearDown
#new一个测试类对象
#第二个测试用例
setUp
assertPreConditions
assertPostConditions
tearDown
...
#测试类基境解构
tearDownAfterClass</code></pre>
因此可在测试类构建阶段使用 <code>setUpBeforeClass</code> 创建一个 <code>App\Example</code> 对象作为静态成员变量(<code>tearDownAfterClass</code> 主要用于资源清理,如关闭文件或数据库连接),然后让各个测试方法共用该实例
<pre class="brush:php;"><code class="language-php">
<?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");
}
}</code></pre>
或者利用 <code>@depends</code> 注解声明执行顺序,并通过 <code>传递参数</code> 的方式满足依赖需求
<pre class="brush:php;"><code class="language-php">
public function testMethod1()
{
$this->assertTrue(true);
return "hello";
}
/**
* @depends testMethod1
*/
public function testMethod2($str)
{
$this->assertEquals("hello", $str);
}</code></pre>
<pre class="brush:php;"><code class="language-php">
#执行模式大概如下
testObj1 = new Test;
$str = testObj1->testMethod1();
testObj2 = new Test;
testObj2->testMethod2($str);</code></pre>
深入理解测试执行模式大有裨益,其他高级特性建议查阅官方文档
<h2>使用配置文件编排测试套件</h2>通过 phpunit.xml 编排测试套件
利用测试套件管理多个测试,编辑 <code>vi phpunit.xml</code>:
<pre class="brush:xml;"><code class="language-xml">
<?xml version="1.0" encoding="UTF-8"?>
./test
./app
随后直接运 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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站