Load data fixtures in setUpBeforeClass with LiipFunctionalTestBundle

945 Views Asked by At

As the title says, I'd like to know how to load the data fixtures in the method setUpBeforeClass. The test class extends Liip\FunctionalTestBundle\Test\WebTestCase.

At the moment I have this:

public function setUp()
{
    $this->client = $this->createClient();
    $this->fixtures = $this->loadFixtures([
        'App\DataFixtures\MyFixtures',
        // more fixtures
    ])->getReferenceRepository();
}

However the tests seem to take too long and there is really no need for the fixtures to be loaded before each test.

When I tried to load the fixtures in setUpBeforeClass I've got an error:

Error: Using $this when not in object context in /home/cezar/phpprojects/livegene/vendor/liip/functional-test-bundle/src/Test/WebTestCase.php:252

A look into the source code of LiipFunctionalTestBundle revealed this snippet:

protected function loadFixtures(array $classNames = [], bool $append = false, ?string $omName = null, string $registryName = 'doctrine', ?int $purgeMode = null): ?AbstractExecutor
{
    $container = $this->getContainer();

    $dbToolCollection = $container->get('liip_functional_test.services.database_tool_collection');
    $dbTool = $dbToolCollection->get($omName, $registryName, $purgeMode, $this);
    $dbTool->setExcludedDoctrineTables($this->excludedDoctrineTables);

    return $dbTool->loadFixtures($classNames, $append);
}

Is it possible to do this, what I wish, and if yes, how could it be achieved?

1

There are 1 best solutions below

1
On

If all you need is a working EntityManager with a (partially) valid database schema to query against, you can use the DoctrineTestHelper provided by the Symfony DoctrineBridge:

public static function setUpBeforeClass()
{
    $config = DoctrineTestHelper::createTestConfiguration();
    $config->setNamingStrategy(new UnderscoreNamingStrategy());
    $entityManager = DoctrineTestHelper::createTestEntityManager($config);
    $schemaTool = new SchemaTool($entityManager);
    $schemaTool->createSchema([
        // List of entities to create schema for
        $entityManager->getClassMetadata(User::class),
        $entityManager->getClassMetadata(Task::class),
    ]);
    static::$entityManager = $entityManager;
}

By default this will use SQLite3 in memory for the connection, but you could also point it to any other database using the config and the appropriate drivers. Be careful to also register any custom DBAL types and LifecycleEvent-listeners you have, as this will change how the data is processed and whether mapping to your entities works.

Now in your tests you can use static::$entityManager as always with the tables or insert test fixtures as you see fit.