【问题标题】:Symfony2: How can I choose the environment to use when running unit tests?Symfony2:如何选择运行单元测试时使用的环境?
【发布时间】:2013-02-26 23:01:20
【问题描述】:

我需要针对两种不同的数据库配置为 Symfony2 应用程序运行单元测试,一种使用 MySQL 数据库,另一种使用 SQLite 数据库。

我目前通过编辑app/config/config_test.yml 来选择运行单元测试时使用的数据库配置。我要么取消注释 MySQL 相关的 db 设置并注释掉 SQLite 相关的 db 设置,反之亦然。

我希望不必这样做,而是有两个配置文件 - 可能是 app/config/config-test-mysql.ymlapp/config/config-test-sqlite.yml - 并在运行测试时从命令行中选择测试环境。

查看了app/phpunit.xml.dist 中的默认 Symfony2 phpunit 配置并查看了配置使用的引导文件 (app/bootstrap.php.cache),我无法确定运行单元测试时环境如何默认为 test

如何选择运行单元测试时使用的环境?

【问题讨论】:

  • 人们何时会停止将涉及数据库的测试作为单元测试?

标签: unit-testing symfony phpunit


【解决方案1】:

我还没有尝试过这个解决方案,但我相信这是一个很好的线索。

我的单元测试类扩展了Symfony\Bundle\FrameworkBundle\Test\WebTestCase,它使您能够创建一个Client,它本身创建一个Kernel

在您的单元测试中,您可以这样做:

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DatabaseRelatedTest extends WebTestCase
{
    private static $client;

    public function setUp()
    {
        // this is the part that should make things work
        $options = array(
            'environment' => 'test_mysql'
        );
        self::$client = static::createClient($options);
        self::$client->request('GET', '/foo/bar'); // must be a valid url
    }
}

您将能够使用客户端容器访问EntityManager 和扩展Connection

self::$client->getContainer()->get('doctrine')

理想的情况是使用phpunit.xml.dist 文件将环境名称传递给setUp 方法。这可能是一个半答案,但我相信这是一个很好的线索。

【讨论】:

  • 这看起来是一个好的开始。我会在接下来的几天里试一试。
猜你喜欢
  • 2015-03-24
  • 1970-01-01
  • 2016-08-19
  • 1970-01-01
  • 2023-03-22
  • 2023-03-17
  • 2015-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多