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
3
Answers
Add
in tests/TestCase.php
You can do this by creating your own TestCase (or edit the original
TestCase,php
), and add these tasks to thecreateApplication
method:Each test should extend this TestCase instead of
IlluminateFoundationTestingTestCase
You can also consider not to cache routes and configuration in your development environment. In your phpunit.xml you can also set the cache driver that is used during testing to a different one than that is used during development, e.g.:
That would drop the necessity to clear the caches before running your tests.
In this answer you can read more about configuration caching during testing. There you can also find a link to a GitHub issue that talks about clearing caches before running tests.
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
andtest
.1. Make a custom command.
php artisan make:command test
2. Edit your test command.
Default path will be
app/Console/Commands/test.php
.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.