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扩展,添加专属命令行选项:
- 编写筛选类:
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; } }
- 按照PHPUnit扩展机制注册这个类,添加
--requires-function命令行参数,后续就能直接用phpunit --requires-function some_function_name来过滤测试了。
注意事项
- 确保你的PHPUnit版本在9.3以上,且PHP版本不低于8.0(这两个版本才支持属性写法)。
- 方法1的回调在不同终端可能需要调整引号格式,比如Windows cmd下要把单引号换成双引号,内部的双引号转义。
内容的提问来源于stack exchange,提问作者Sonny
相关产品推荐
相关产品推荐

