How to setup a database for test environment in Symfony 4
Asked Answered
C

1

6

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.

Cameleer answered 5/6, 2018 at 10:52 Comment(1)
O
10

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

Oblast answered 5/6, 2018 at 12:18 Comment(3)
I tried something like that, but it seems the passthu'ed console command does not run the the environment defined by my <env ... entries in phpunit.xml...Transship
There is a hierarchy which values are being used, so it could be that your project's .env.test(.local) file or your system environment overwrites the settings from the phpunit.xml.dist.Oblast
Ah, no I just found out that it is impossible to define <env... commands inside testsuites, and I was trying this. Thanks anyway!Transship

© 2022 - 2024 — McMap. All rights reserved.