ubuntu

Ubuntu PHPStorm如何进行单元测试

小樊
36
2025-10-16 20:45:07
栏目: 编程语言

1. 安装PHPUnit
在Ubuntu终端中,通过Composer全局安装PHPUnit(推荐方式,便于项目级管理):

composer global require phpunit/phpunit

安装完成后,将Composer的全局bin目录添加到系统PATH中(如使用bash,编辑~/.bashrc~/.zshrc文件,添加export PATH="$PATH:$HOME/.composer/vendor/bin",然后运行source ~/.bashrcsource ~/.zshrc使更改生效)。也可通过Ubuntu软件仓库安装(sudo apt-get install phpunit/phpunit),但全局安装更灵活。

2. 配置PhpStorm使用PHPUnit
打开PhpStorm,进入File > Settings(或PhpStorm > Preferences,macOS用户),导航至Tools > PHP > PHPUnit

3. 创建测试目录与测试用例
在项目根目录下创建tests目录(用于存放所有测试文件,符合PHPUnit约定)。新建测试类文件(如ExampleTest.php),内容需继承PHPUnit\Framework\TestCase,且测试方法以test开头:

<?php
use PHPUnit\Framework\TestCase;

class ExampleTest extends TestCase
{
    public function testExample()
    {
        $this->assertTrue(true); // 断言示例:验证true等于true
    }

    public function testAddition()
    {
        $this->assertEquals(4, 2 + 2); // 断言示例:验证2+2等于4
    }
}

测试类命名需遵循类名Test.php规则(如UserModelTest.php对应UserModel类)。

4. 编写phpunit.xml配置文件
在项目根目录下创建phpunit.xml文件,定义测试套件、白名单等配置(示例):

<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php" colors="true">
    <testsuites>
        <testsuite name="Default Test Suite">
            <directory suffix="Test.php">./tests</directory> <!-- 测试文件目录及后缀 -->
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./src</directory> <!-- 被测试代码目录(白名单) -->
        </directory>
    </filter>
</phpunit>

5. 运行单元测试
PhpStorm提供多种运行测试的方式:

6. 调试单元测试
若测试失败或需要排查问题,可使用PhpStorm的调试功能:

注意事项

0
看了该问题的人还看了