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

Laravel 10中Laravel Modules测试无法被PHPUnit检测的问题

Laravel 10 + Laravel Modules 配置PHPUnit检测模块测试

一、调整测试套件配置(让PHPUnit识别模块测试)

Laravel 10默认配套的PHPUnit 10对目录匹配语法做了调整,之前的递归匹配写法可能不再生效。替换phpunit.xml中的<testsuites>节点为以下内容即可:

<testsuites>
    <!-- 保留项目默认的测试套件 -->
    <testsuite name="Unit">
        <directory suffix="Test.php">./tests/Unit</directory>
    </testsuite>
    <testsuite name="Feature">
        <directory suffix="Test.php">./tests/Feature</directory>
    </testsuite>

    <!-- 添加模块单元测试套件 -->
    <testsuite name="Module Unit">
        <directory suffix="Test.php">./Modules/*/Tests/Unit</directory>
    </testsuite>
    <!-- 添加模块功能测试套件 -->
    <testsuite name="Module Feature">
        <directory suffix="Test.php">./Modules/*/Tests/Feature</directory>
    </testsuite>
</testsuites>

如果想把所有模块测试合并为一个套件,也可以这样写:

<testsuite name="Modules">
    <directory suffix="Test.php">./Modules/*/Tests</directory>
</testsuite>

注意:这里用*匹配单级目录(对应每个模块文件夹),而非**。同时要确保测试文件后缀为Test.php,类名与文件名完全一致,且命名空间正确(比如Modules\Shop\Tests\Unit\ProductTest对应文件Modules/Shop/Tests/Unit/ProductTest.php)。

二、修复覆盖率配置(解决Laravel 8配置报错)

PHPUnit 10修改了覆盖率配置的语法规则,原Laravel 8中的写法会触发报错,改用以下配置即可:

<coverage processUncoveredFiles="true">
    <include>
        <!-- 统计模块源码的覆盖率 -->
        <directory suffix=".php">./Modules/*/app</directory>
        <!-- 若要统计测试文件本身,可取消下面注释 -->
        <!-- <directory suffix="Test.php">./Modules/*/Tests</directory> -->
    </include>
</coverage>

三、额外验证步骤

  • 确认模块测试类继承了PHPUnit\Framework\TestCase(纯单元测试)或Laravel的Tests\TestCase(需要Laravel环境的功能测试)
  • 运行测试时可指定套件验证:./vendor/bin/phpunit --testsuite "Modules"
  • 执行php artisan config:clear清除配置缓存,避免影响测试加载

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 04:44:54