You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过phpunit.xml结合注解/组控制测试套件的测试用例包含与排除

用PHPUnit组注解+XML配置控制测试用例的包含/排除

别急,这事儿其实很好搞定,我帮你理清楚正确的配置方式,以及可能踩的坑:

第一步:给测试用例标记组注解

首先要在你的测试类或测试方法上添加@group注解,注意必须是文档注释格式(双星号开头),不然PHPUnit识别不到:

<?php

namespace Tests;

use PHPUnit\Framework\TestCase;

/**
 * @group fast
 * @group unit
 */
class FastUnitTest extends TestCase
{
    /**
     * @group critical
     */
    public function testSomethingCritical()
    {
        // ... 测试逻辑
    }

    public function testSomethingElse()
    {
        // ... 这个方法会继承类上的fast和unit组
    }
}

/**
 * @group slow
 */
class SlowIntegrationTest extends TestCase
{
    public function testLongRunningProcess()
    {
        // ... 测试逻辑
    }
}

第二步:在phpunit.xml中配置组规则

接下来要把组的包含/排除规则写在phpunit.xml的<groups>标签里,注意这个标签要放在<phpunit>根标签内部,和<testsuites>同级:

示例1:只运行特定组的测试

如果只想运行标记为fast和critical的测试,配置如下:

<phpunit bootstrap="vendor/autoload.php">
    <testsuites>
        <testsuite name="All Tests">
            <directory>./tests</directory>
        </testsuite>
    </testsuites>

    <groups>
        <include>
            <group>fast</group>
            <group>critical</group>
        </include>
    </groups>
</phpunit>

示例2:排除特定组的测试

如果想运行所有测试,除了slow组的,配置如下:

<phpunit bootstrap="vendor/autoload.php">
    <testsuites>
        <testsuite name="All Tests">
            <directory>./tests</directory>
        </testsuite>
    </testsuites>

    <groups>
        <exclude>
            <group>slow</group>
        </exclude>
    </groups>
</phpunit>

常见问题排查(为什么你的配置没生效?)

  • 注解格式错误:一定要用/** @group xxx */,不能用/* @group xxx */或者单行注释// @group xxx,PHPUnit只会识别文档注释里的组标记。
  • 测试套件没覆盖到目标文件:确保<testsuites>里的<directory>包含了所有带组注解的测试文件,不然PHPUnit根本扫描不到这些测试,组规则自然无效。
  • XML结构错误:<groups>标签必须直接放在<phpunit>根标签下,不能嵌套在<testsuites>或者其他标签里。
  • 缓存问题:有时候PHPUnit会缓存配置,你可以试试删除./.phpunit.cache目录,然后重新运行测试。

这样配置后,直接运行phpunit命令(不用额外参数),就会按照你在XML里设置的组规则来执行测试,完全不用移动文件或者多次调用CLI啦!

内容的提问来源于stack exchange,提问作者Sam Anthony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:19:49