PHP PHPUnit安装与测试入门教程
本示例详细解析了PHP中基于PHPUnit框架的单元测试基础操作,旨在为开发者提供实用的参考指南。
在Windows开发环境中,执行PHP单元测试主要依赖PHPUnit工具库。
环境搭建
首先访问官网 https://phpunit.de/ 获取PHPUnit资源。需根据本地PHP版本选择匹配的安装包,例如本地为PHP5.5时,可选用PHPUnit4.8。下载后获得 phpunit-4.8.35.phar 文件,将其存放至指定目录(如 D:\phpunit),并重命名为 phpunit.phar。接着配置系统环境变量:右键点击“我的电脑”选择属性,进入高级系统设置中的环境变量,编辑Path变量并在末尾追加该文件的所在路径(即 D:\phpunit)。
按下 Win+R 键打开运行窗口,输入 cmd 启动命令行,并切换工作目录至 D:\phpunit。
cd /d D:\phpunit
执行安装命令
echo @php "%~dp0phpunit.phar" %* > phpunit.cmd
验证安装状态
phpunit --version
若命令行输出包含PHPUnit的版本详情,则表明安装成功。例如显示内容为:PHPUnit 4.8.35 by Sebastian Bergmann and contributors.。
功能验证
首先创建一个待测类文件 Human.php,其中定义一个 eat 方法,该方法返回字符串 'eating'。
<?php
class Human
{
public function eat()
{
return 'eating';
}
}
</code></pre>
接着创建 PHPUnit 测试文件 test1.php,用于测试 Human 类的 eat 方法。此文件必须引入 Human.php 及 PHPUnit 相关依赖。
<pre class="brush:php;"><code class="language-php">
<?php
include 'Human.php';
use PHPUnit\Framework\TestCase;
class TestHuman extends TestCase
{
public function testEat()
{
$human = new Human;
$this->assertEquals('eating', $human->eat());
}
}
?>
代码中使用 assertEquals 方法进行断言,校验 eat 方法的返回值是否严格等于 'eating'。若一致则测试通过,否则报错。执行测试时,需在命令行中导航至 test1.php 所在目录,并运行相应命令。
phpunit test1.php
预期输出信息如下:
PHPUnit 4.8.35 by Sebastian Bergmann and contributors. . Time: 202 ms, Memory: 14.75MB OK (1 test, 1 assertion)
上述输出表明断言测试通过,即实际返回值与预期参数值完全吻合。
希望本例所述内容能对各位PHP程序员的开发工作有所助益。