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

Laravel 9中如何在所有测试执行前仅执行一次缓存清理命令?

Laravel 9 + PHPUnit 9.5 全局测试前置清理缓存方案

要在所有测试执行前一次性清理缓存(而非单个测试/测试类),可以通过以下两种可靠方案实现:

方案一:使用PHPUnit测试套件钩子

  1. 在项目根目录创建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');
    }
}
  1. 修改项目根目录的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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 09:32:44