I use Laravel 8 with PHPUnit 9.3.3
Now I has written in CreatesApp.php:
namespace Tests;
use AppModelsUser;
use IlluminateContractsConsoleKernel;
use IlluminateSupportFacadesArtisan;
trait CreatesApplication
{
    /**
     * Creates the application.
     *
     * @return IlluminateFoundationApplication
     */
    public function createApplication()
    {
        $app = require __DIR__.'/../bootstrap/app.php';
        $app->make(Kernel::class)->bootstrap();
        Artisan::call('migrate:reset');
        Artisan::call('migrate');
        AppModelsUser::factory(10)->create();
        AppModelsPost::factory(10)->create();
        return $app;
    }
}
And this code executes every test and I want this code executed ONLY before testing:
Artisan::call('migrate:reset');
Artisan::call('migrate');
AppModelsUser::factory(10)->create();
AppModelsPost::factory(10)->create();
Advertisement
Answer
If you want to execute some commands only once at startup – you can bootstrap tests with your own boostraper: docs
But, your way is not correct:
Tests MUST be isolated: migration MUST be executed for each tests
For this – add DatabaseMigrations trait to your tests.
use DatabaseMigrations;
For create entities – use seeders
For seeding database for tests – overwrite setUp method
public function setUp(): void { parent::setUp(); $this->seed(); }
Btw, maybe you frustrated about tests speed with migrations – look at this article – it’s dramatically improved performance