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

PHPUnit:如何运行带有指定RequiresFunction属性的测试用例

只运行指定RequiresFunction属性的PHPUnit测试用例

方法1:用--filter命令行参数结合反射筛选

PHPUnit没有直接提供针对RequiresFunction属性的过滤参数,但可以通过--filter的回调功能实现精准筛选。执行以下命令(把target_function换成你要指定的函数名):

phpunit --filter 'function($test) {
    $reflection = new ReflectionMethod($test);
    $attrs = $reflection->getAttributes(\PHPUnit\Framework\Attributes\RequiresFunction::class);
    foreach ($attrs as $attr) {
        if ($attr->getArguments()[0] === "target_function") {
            return true;
        }
    }
    return false;
}'

原理是通过反射获取测试方法的RequiresFunction属性,对比属性参数是否匹配目标函数名,只有符合条件的测试才会被执行。

方法2:自定义筛选器(适合频繁使用场景)

如果需要经常按这个规则筛选测试,可以写个简单的PHPUnit扩展,添加专属命令行选项:

  1. 编写筛选类:
use PHPUnit\Framework\Test;
use PHPUnit\Runner\Filter\Filter;

class RequiresFunctionFilter extends Filter
{
    private string $targetFunc;

    public function __construct(string $targetFunc)
    {
        $this->targetFunc = $targetFunc;
    }

    public function accept(Test $test): bool
    {
        if (!$test instanceof \PHPUnit\Framework\TestCase) {
            return false;
        }
        $method = new ReflectionMethod($test::class, $test->getName(false));
        foreach ($method->getAttributes(\PHPUnit\Framework\Attributes\RequiresFunction::class) as $attr) {
            if ($attr->getArguments()[0] === $this->targetFunc) {
                return true;
            }
        }
        return false;
    }
}
  1. 按照PHPUnit扩展机制注册这个类,添加--requires-function命令行参数,后续就能直接用phpunit --requires-function some_function_name来过滤测试了。

注意事项

  • 确保你的PHPUnit版本在9.3以上,且PHP版本不低于8.0(这两个版本才支持属性写法)。
  • 方法1的回调在不同终端可能需要调整引号格式,比如Windows cmd下要把单引号换成双引号,内部的双引号转义。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 01:12:10