PHPUnit 10.5抽象类警告问题求助(PHP7升级至PHP8后)
解决PHP 8升级后PHPUnit抽象测试基类的警告问题
问题根源
你的BaseApiTest.php文件后缀符合PHPUnit测试类的扫描规则(Test.php),导致PHPUnit尝试将这个抽象类作为测试用例加载,但抽象类无法被实例化,因此抛出警告。你之前在source节点下的排除配置只针对源码目录(src),对测试用例的扫描不生效。
解决方案
方案1:修改基类文件名(推荐)
将BaseApiTest.php重命名为不带Test后缀的名称,比如BaseApiTestCase.php,这样PHPUnit的扫描规则就不会把它识别为测试用例文件:
<?php namespace app\tests\cases\api; use accounts\test\Integration; use PHPUnit\DbUnit\DataSet\YamlDataSet; abstract class BaseApiTestCase extends Integration { } ?>
所有继承该类的测试用例同步修改引用即可。
方案2:在测试套件中排除该文件
修改phpunit.xml的testsuite节点,添加排除规则,指定跳过这个抽象类文件:
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="phpunit.xsd" bootstrap="tests/bootstrap.php" cacheDirectory=".phpunit.cache" beStrictAboutOutputDuringTests="true" failOnRisky="true" failOnWarning="true" colors="true"> <testsuite name="My Test Suite"> <directory suffix="Test.php">./tests</directory> <!-- 添加这行排除抽象类文件 --> <exclude>./tests/cases/api/BaseApiTest.php</exclude> </testsuite> <source restrictDeprecations="true" restrictNotices="true" restrictWarnings="true"> <include> <directory suffix=".php">src</directory> </include> </source> </phpunit>
注意路径要和你的实际目录结构匹配,确保PHPUnit能定位到该文件。
方案3:临时关闭警告触发失败(不推荐)
如果只是临时规避,可以将failOnWarning改为false,但这会忽略所有警告信息,可能错过其他潜在问题:
failOnWarning="false"
内容的提问来源于stack exchange,提问作者Steve
相关产品推荐
相关产品推荐

