Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

257
Vistas
Have setup method run only once

I have:

1. IntegrationTestCase extends TestCase  
2. UnitTestCase extends TestCase
3. AcceptanceTestCase extends TestCase  

In these I have quite a lot of non-static methods which are used in a lot of tests. All of my Test classes extend one of these 3 classes.

Now in a lot of Test classes I have a setUp method which preps the data and services needed and assigns them to class variables:

class SomeTestClass extends IntegrationTestCase
{
    private $foo;

    public function setUp()
    {
        parent::setUp();

        $bar = $this->createBar(...);
        $this->foo = new Foo($bar);
    }

    public function testA() { $this->foo...; }  
    public function testB() { $this->foo...; }
}

Problem is setUp is ran for each test defeating what I wanted to do and if what setUp method does takes a long time this is multiplied by the number of test methods.

Using public function __construct(...) { parent::__construct(..); ... } creates a problem because now lower level methods and classes from Laravel are not available.

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

For the next person running into this issue:

I had the problem that I wanted to migrate the database before running my tests but I didn't want the database to be migrated after each single test because the execution time would be way too high.

The solution for me was using a static property to check if the database was already migrated:

class SolutionTest extends TestCase
{
    protected static $wasSetup = false;

    protected function setUp()
    {
        parent::setUp();

        if ( ! static::$wasSetup) {
            $this->artisan('doctrine:schema:drop', [
                '--force' => true
            ]);

            $this->artisan('doctrine:schema:create');

            static::$wasSetup = true;
        }
    }
}
about 4 years ago · Santiago Trujillo Denunciar

0

Solution given by Saman Hosseini and similar didn't workout for me. Using the static property to flag getting reset for the next test class.

To overcome this I've wrote separate test class to test the test database connection & initialize the test database for once & made sure this runs before all the other tests

<?php

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Artisan;

/**
 * @runTestsInSeparateProcesses
 */
class DatabaseConnectionTest extends TestCase
{
    /**
     * Test the database connection
     *
     * @return void
     */
    public function testDatabaseConnection()
    {
        $pdo = DB::connection()->getPdo();
        $this->assertNotNull($pdo);
    }

    /**
     * Initialize the test database for once
     *
     * @return void
     */
    public function testInititializeTestDatabase()
    {
        Artisan::call('migrate:fresh');
        Artisan::call('db:seed');
    }
}

about 4 years ago · Santiago Trujillo Denunciar

0

I am not sure what issues you see for setUpBeforeClass is static except for the one mentioned by Mark Baker. I assume you do know what you are doing, though. Here is a sample of possible usage.

class BeforeAllTest extends PHPUnit_Framework_TestCase
{
    private static $staticService;
    private $service; // just to use $this is tests

    public static function setUpBeforeClass() {
        self::createService();
    }

    public static function createService(){
        self::$staticService = 'some service';
    }

    /**
     * just to use $this is tests
     */
    public function setUp(){
        $this->service = self::$staticService;
    }

    public function testService(){
        $this->assertSame('some service', $this->service);
    }
}

UPDATE: just somewhat similar approach you can see at https://phpunit.de/manual/current/en/database.html (search for 'Tip: Use your own Abstract Database TestCase'). I am sure you are already using it since you are doing intensive db testing. But nobody restricts this way for db-issues only.

UPDATE2: well, I guess you would have to use smth like self::createService instead of $this->createService (I've updated the code above).

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda