【问题标题】:remove test database when tests ends (Symfony / PHP Unit)测试结束时删除测试数据库(Symfony / PHP Unit)
【发布时间】:2021-11-04 02:46:06
【问题描述】:

我正在使用 PHPUnit (9.5)Symfony (5.3)

对于我的测试,我使用 config/packages/test/doctrine.yaml 中的默认测试数据库配置:

doctrine:
    dbal:
        # "TEST_TOKEN" is typically set by ParaTest
        dbname_suffix: '_test%env(default::TEST_TOKEN)%'

所以我的测试使用与 prod 相同的数据库,后缀为“_test”。

我在 tests/bootstrap.php 中添加了一些代码,以便在每次测试运行之前自动创建/重置数据库:

// delete database if exists, then create
passthru('php bin/console doctrine:database:drop --env=test --force --if-exists');
passthru('php bin/console doctrine:database:create --env=test');

// run migrations
passthru('php bin/console doctrine:migrations:migrate --env=test -n');

我使用 dama/doctrine-test-bundle 进行每个测试的自动交易。



效果很好,但我有一个问题:

有没有办法在测试运行结束时删除数据库? (就像我在 bootstrap.php 中所做的那样)

【问题讨论】:

    标签: symfony testing doctrine-orm phpunit


    【解决方案1】:

    我了解到您的 bootstrap.php 文件在测试之前正在运行,您需要一个解决方案来在测试之后启动某些东西。

    首先,create a command 删除测试数据库。

    无论如何,如果您不在显式测试环境中(因为这意味着您在生产环境中),请务必小心,让命令中的代码停止所有执行。

    然后,您可以在 chain of scripts 中进行测试后更改您的 composer.json 文件以启动创建的命令。

    这是一个例子

        "scripts": {
            "test-and-remove": [
                "@putenv APP_ENV=test",
                "phpunit --configuration phpunit.xml",
                "php bin/console app:drop-test-database"
            ],
    

    那么你只需要通过这个新命令启动你的测试:

    composer test-and-remove
    

    【讨论】:

    • 谢谢,但我已经在 bootstrap.php 中完成了这项工作。这段代码在测试开始时运行,我需要在测试结束时运行这段代码。
    • 对不起,我不明白。我更新了我的答案。希望对你有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    相关资源
    最近更新 更多