Laravel 9中如何在所有测试执行前仅执行一次缓存清理命令?
Laravel 9 + PHPUnit 9.5 全局测试前置清理缓存方案
要在所有测试执行前一次性清理缓存(而非单个测试/测试类),可以通过以下两种可靠方案实现:
方案一:使用PHPUnit测试套件钩子
- 在项目根目录创建
tests/Helpers/TestCacheCleaner.php文件,写入以下代码:
<?php namespace Tests\Helpers; use PHPUnit\Runner\BeforeTestSuiteHook; use Illuminate\Contracts\Console\Kernel; class TestCacheCleaner implements BeforeTestSuiteHook { public function execute(\PHPUnit\Framework\TestSuite $suite): void { // 初始化Laravel应用实例 $app = require __DIR__.'/../../bootstrap/app.php'; $app->make(Kernel::class)->bootstrap(); // 执行指定缓存清理命令 $app->make(Kernel::class)->call('cache:clear'); $app->make(Kernel::class)->call('route:clear'); $app->make(Kernel::class)->call('config:clear'); } }
- 修改项目根目录的
phpunit.xml配置文件,在<phpunit>标签内添加钩子配置:
<extensions> <extension class="Tests\Helpers\TestCacheCleaner"/> </extensions>
配置完成后,PHPUnit启动测试套件时会自动执行该钩子,一次性完成所有缓存清理操作。
方案二:直接在PHPUnit配置中添加前置命令
如果觉得钩子配置繁琐,可直接修改phpunit.xml,将清理命令设置为测试启动的前置操作:
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd" bootstrap="vendor/autoload.php" colors="true"> <!-- 保留原有其他配置 --> <php> <server name="APP_ENV" value="testing"/> <!-- 添加以下三个清理命令 --> <exec command="php artisan cache:clear"/> <exec command="php artisan route:clear"/> <exec command="php artisan config:clear"/> </php> </phpunit>
这种方式会在PHPUnit加载所有测试前,先执行指定的artisan命令,实现全局一次性缓存清理。
注意:两种方案均确保操作仅在整个测试套件启动时执行一次,不会在单个测试类/方法前重复触发,完全匹配需求。
内容的提问来源于stack exchange,提问作者Majesty
相关产品推荐
相关产品推荐

