Search code examples
laravelphpunit

How to execute a command once before all tests?


I'm looking a solution to clear cache in Laravel, before starting all the tests (please note I mean ALL tests, not every single test):

    $this->artisan('cache:clear');
    $this->artisan('route:clear');
    $this->artisan('config:clear');

P.S. Laravel 9 and PHPUnit 9.5


Solution

  • As I known, no such way to do this, because this is not the range of unit tests.

    Unit tests designed to setting same environment for each tests, environment of all tests is not its responsibility.

    But you can still work around by make a custom command to call config:clear and test.

    1. Make a custom command.

    php artisan make:command test

    2. Edit your test command.

    Default path will be app/Console/Commands/test.php.

    ...
    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->call('cache:clear');
        $this->call('route:clear');
        $this->call('config:clear');
        $this->call('test');
    }
    

    3. Call unit tests by your own test command.

    If you didn't change the default $signature, app:test will be the default command you just created.

    Run php artisan app:test to call unit tests.