PHPUnit v10嵌套测试套件导致测试结果重复问题咨询
PHPUnit 10 嵌套测试套件导致测试重复计数的问题
问题场景
当你在phpunit.xml中定义包含嵌套目录的测试套件时:
<testsuite name="Unit Tests"> <directory suffix="Test.php">tests/Unit</directory> </testsuite> <testsuite name="Integration Tests"> <directory suffix="Test.php">tests/Integration</directory> </testsuite> <testsuite name="PubMed Tests"> <directory suffix="Test.php">tests/Integration/PubMed</directory> </testsuite>
编写简单测试类:
use PHPUnit\Framework\TestCase; class PHPUnitDoublingTest extends TestCase { public function testPhpUnitDoublesEverything() { $this->assertEquals(1, 1); } }
执行过滤测试的命令phpunit --filter testPhpUnitDoublesEverything时会出现异常:
- 测试文件放在
tests/Unit/下:正常输出OK (1 test, 1 assertion) - 测试文件放在
tests/Integration/PubMed/下:输出OK (2 tests, 2 assertions),明明只有一个测试却被统计了两次
这个问题是PHPUnit 10升级后才出现的,PHPUnit 9中没有该现象,移除嵌套的测试套件配置后恢复正常。
原因
这不是PHPUnit 10的设计预期,而是版本升级后测试套件扫描逻辑的变化:PHPUnit 9会自动对多个套件中重复包含的测试文件去重,而PHPUnit 10默认不再做去重处理,导致同一个测试被多个包含它的套件重复统计。
解决办法
1. 调整套件配置,避免重复包含目录
修改phpunit.xml,让父级的Integration Tests套件排除子目录PubMed,确保每个测试文件只被一个套件覆盖:
<testsuite name="Integration Tests"> <directory suffix="Test.php">tests/Integration</directory> <exclude>tests/Integration/PubMed</exclude> </testsuite> <testsuite name="PubMed Tests"> <directory suffix="Test.php">tests/Integration/PubMed</directory> </testsuite>
2. 执行测试时指定目标套件
如果不需要一次性运行所有套件,执行命令时明确指定要运行的测试套件,这样只会扫描该套件下的目录,避免重复统计:
phpunit --testsuite "PubMed Tests" --filter testPhpUnitDoublesEverything
内容的提问来源于stack exchange,提问作者sfsacc
相关产品推荐
相关产品推荐

