Laravel 8+PHP8.1执行php artisan test报错,求解决方法
问题背景
- Laravel版本:8
- PHP版本:8.1
报错情况
- 执行
php artisan test时,报错:Command "tests" is not defined. - 添加
nunomaduro/collision依赖后,出现如下错误:NunoMaduro\Collision\Adapters\Laravel\Exceptions\RequirementsException Running Collision ^5.0 artisan test command requires at least PHPUnit ^9.0.
问题根源
深入排查依赖发现:PHP8.1官方推荐PHPUnit ^10,但Laravel8兼容的nunomaduro/collision版本要求PHPUnit ^9,而项目已上线无法升级Laravel,需在现有环境下正常执行php artisan test。
已尝试但无效的方案
- 强制安装
nunomaduro/collision6.0版本 → 因Laravel框架依赖限制安装失败 - 注释版本锁相关代码 → 出现错误:
option unknown --printer
可行解决思路
1. 直接使用PHPUnit原生命令
artisan test本质是对PHPUnit命令的封装,直接执行以下命令即可跳过Collision的版本冲突:
# Linux/Mac ./vendor/bin/phpunit # Windows vendor\bin\phpunit
2. 适配兼容版本的依赖组合
PHPUnit 9.5+版本本身支持PHP8.1,因此可以锁定PHPUnit为^9.5,同时安装对应兼容的Collision 5.x版本:
修改composer.json的require-dev字段:
"require-dev": { "nunomaduro/collision": "^5.11", "phpunit/phpunit": "^9.5" }
执行更新命令:
composer update nunomaduro/collision phpunit/phpunit
此方案能同时满足Laravel8、PHP8.1、Collision和PHPUnit的依赖要求,恢复artisan test命令的正常使用。
3. 自定义Artisan测试命令
如果不想调整依赖,可新建一个自定义命令直接调用PHPUnit:
- 在
app/Console/Commands目录下创建RunTests.php文件:
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Symfony\Component\Process\Process; class RunTests extends Command { protected $signature = 'test:run'; protected $description = '运行PHPUnit测试(绕过Collision依赖限制)'; public function handle() { $process = Process::fromShellCommandline('./vendor/bin/phpunit'); $process->run(function ($type, $buffer) { $this->output->write($buffer); }); return $process->getExitCode(); } }
- 执行命令运行测试:
php artisan test:run
4. 临时绕过Collision版本校验(风险较高)
仅建议测试环境临时使用:找到vendor/nunomaduro/collision/src/Adapters/Laravel/Commands/TestCommand.php,注释掉版本校验的代码段:
// 注释掉以下内容 // if (! $this->getLaravel()->make(PhpUnit::class)->isVersionGreaterThanOrEqualTo('9.0')) { // throw RequirementsException::phpUnitVersionMissing(); // }
此方案会在composer更新后失效,且可能引发未知问题,不推荐长期使用。
内容的提问来源于stack exchange,提问作者Rowlando13
相关产品推荐
相关产品推荐

