Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup a database for test environment in Symfony 4

I feel confused about how to setup a database for the test envrionment in symfony 4. I used to deal with it in config_test.yml file in symfony 3 and below.

What is the best practice ? Should I recreate a doctrine.yaml file in config/packages/test ?

The documentation mentions how to run functional test using a database by editing the phpunit config :

<phpunit>
    <php>
        <!-- the value is the Doctrine connection string in DSN format -->
        <env name="DATABASE_URL" value="mysql://USERNAME:[email protected]/DB_NAME" />
    </php>
    <!-- ... -->
</phpunit>

However it does not feet my needs since I need to be able to update schema/load fixtures to the test env.

like image 989
Ousmane Avatar asked Jun 05 '18 10:06

Ousmane


1 Answers

For what you want to do I usually create a custom test bootstrap that runs the required doctrine commands and looks something like this:

# tests/bootstrap.php
<?php

if (isset($_ENV['BOOTSTRAP_RESET_DATABASE']) && $_ENV['BOOTSTRAP_RESET_DATABASE'] == true) {
    echo "Resetting test database...";
    passthru(sprintf(
        'php "%s/../bin/console" doctrine:schema:drop --env=test --force --no-interaction',
        __DIR__
    ));
    passthru(sprintf(
        'php "%s/../bin/console" doctrine:schema:update --env=test --force --no-interaction',
        __DIR__
    ));
    passthru(sprintf(
        'php "%s/../bin/console" doctrine:fixtures:load --env=test --no-interaction',
        __DIR__
    ));
    echo " Done" . PHP_EOL . PHP_EOL;
}
require __DIR__.'/../vendor/autoload.php';

In my phpunit.xml.dist I addd the env variable:

<env name="DATABASE_URL" value="sqlite:///%kernel.project_dir%/var/test.db"/>
<env name="BOOTSTRAP_RESET_DATABASE" value="1" />

If you want to see a basic example I have a Symfony 4 demo project that uses this to set up a basic test database that is used by Functional Tests using the web test case. You can find it on GitHub: dbrumann/product-api

like image 164
dbrumann Avatar answered Sep 23 '22 04:09

dbrumann