如何在Symfony 4中为测试环境设置数据库 [英] How to setup a database for test environment in Symfony 4
问题描述
我对如何为symfony 4中的测试环境设置数据库感到困惑.我曾经在symfony 3及以下版本的 config_test.yml 文件中处理过该数据库.
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.
最佳做法是什么?我应该在 config/packages/test中重新创建一个 doctrine.yaml 文件吗?
What is the best practice ? Should I recreate a doctrine.yaml file in config/packages/test ?
文档提到了如何通过编辑phpunit config来使用数据库运行功能测试:
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:PASSWORD@127.0.0.1/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.
推荐答案
对于您要执行的操作,我通常创建一个自定义的测试引导程序,该引导程序运行所需的教义命令并看起来像这样:
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';
在我的 phpunit.xml.dist
中,添加了env变量:
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" />
如果您想看一个基本示例,我有一个Symfony 4演示项目,该项目使用它来建立一个基本测试数据库,供功能测试使用Web测试用例使用.您可以在GitHub上找到它: dbrumann/product-api
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
这篇关于如何在Symfony 4中为测试环境设置数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!