Skip to content
Advertisement

PHPUnit Larvel execute ONCE before testing

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:

  1. Tests MUST be isolated: migration MUST be executed for each tests

  2. For this – add DatabaseMigrations trait to your tests.

    use DatabaseMigrations;
    
  3. For create entities – use seeders

  4. 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

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement