1. 准备工作:安装PHP与Composer
在Ubuntu上使用PhpStorm进行单元测试前,需确保系统已安装PHP(建议版本≥7.4)和Composer(PHP依赖管理工具)。可通过以下命令安装:
sudo apt update
sudo apt install php php-cli php-mbstring php-xml composer
安装完成后,通过php -v和composer -V验证安装是否成功。
2. 安装PHPUnit
PHPUnit是PHP主流单元测试框架,推荐通过Composer以项目依赖形式安装(避免全局污染):
cd /path/to/your/project # 进入项目根目录
composer require --dev phpunit/phpunit
安装后,PHPUnit的可执行文件会位于项目根目录的vendor/bin/phpunit路径下。
3. 配置PhpStorm的PHPUnit
打开PhpStorm,进入File > Settings > Tools > PHP > PHPUnit(Windows/Linux路径),完成以下设置:
vendor/bin/phpunit(若全局安装,可选择系统PATH中的路径,如/usr/local/bin/phpunit);phpunit.xml(后续会创建);File > Settings > Languages & Frameworks > PHP > CLI Interpreter,选择Ubuntu系统的PHP路径(如/usr/bin/php)或WSL中的PHP路径(若使用WSL)。4. 创建phpunit.xml配置文件
在项目根目录下创建phpunit.xml,定义测试范围、Bootstrap文件及代码覆盖率规则(示例):
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php" colors="true">
<testsuites>
<testsuite name="Application Tests">
<!-- 指定测试文件目录(suffix指定测试类后缀) -->
<directory suffix="Test.php">./tests</directory>
</testsuite>
</testsuites>
<filter>
<!-- 白名单:指定需要测试的源代码目录 -->
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./src</directory>
</whitelist>
</filter>
</phpunit>
此配置会自动加载vendor/autoload.php(Composer自动加载),并扫描tests目录下所有以Test.php结尾的测试文件,同时覆盖src目录下的PHP源代码。
5. 编写测试用例
在项目根目录下创建tests目录(与phpunit.xml中的<directory>配置一致),新建测试类文件(如ExampleTest.php)。测试类需继承PHPUnit\Framework\TestCase,且测试方法以test开头(PHPUnit会自动识别):
<?php
namespace Tests;
use PHPUnit\Framework\TestCase;
class ExampleTest extends TestCase
{
public function testBasicAssertions()
{
// 断言相等
$this->assertEquals(4, 2 + 2);
// 断言为真
$this->assertTrue(true);
// 断言包含
$this->assertStringContainsString('foo', 'foobar');
}
public function testArrayContains()
{
$array = ['apple', 'banana', 'orange'];
$this->assertContains('banana', $array);
}
}
测试类文件名需遵循{ClassName}Test.php规范(如UserModelTest.php对应UserModel类)。
6. 运行单元测试
PhpStorm提供多种运行测试的方式:
testBasicAssertions),选择Run 'testBasicAssertions';ExampleTest.php),选择Run 'ExampleTest';tests目录或项目根目录,选择Run 'All Tests';Terminal窗口,输入vendor/bin/phpunit(或phpunit,若全局安装),即可运行所有测试。7. 查看与调试测试结果
测试运行后,结果会显示在PhpStorm底部的Run工具窗口中:
Debug 'testBasicAssertions',即可进入调试模式(支持变量查看、单步执行等功能)。8. 可选:集成WSL环境(针对Ubuntu WSL用户)
若使用Ubuntu的WSL(Windows Subsystem for Linux)作为开发环境,需配置PhpStorm使用WSL的PHP CLI和PHPUnit:
File > Settings > Languages & Frameworks > PHP > CLI Interpreter,点击+→From WSL,选择WSL中的Ubuntu发行版及PHP路径(如/usr/bin/php);PHPUnit设置中,将“PHPUnit executable”指向WSL中的路径(如/mnt/c/Users/YourName/projects/myproject/vendor/bin/phpunit);php.ini中添加Xdebug配置(如xdebug.remote_host=localhost,xdebug.remote_port=9001),并在PhpStorm中开启Xdebug调试功能。