11

我仍在进行 PHP 单元测试以测试我的 symfony2 控制器。我的测试类是 WebTestCase 的派生,并且测试正在执行 GET 或 POST 请求,以检查一切是否正常。我想测试所有底层,但我不想让我的数据库被测试弄乱。我不想使用模型,而是使用内存中的 SQLite db,我可以在其中设置测试场景来检查所有修改。我发现了很多提示如何使用学说 1.x 做到这一点,但它们不再起作用了。所以我想要这样的东西:

class BlahblahTest extends WebTestCase {
    public function testXXXYYY() {
        // 1. Setup a new database with SQLite:memory:
        // 2. create the database and all tables according the entities in my project
        $this->createTestScenario(); // 3.
        $crawler = $this->client->request('GET', '/testpage');  // 4.
        // 5. Lots of checks against the database and / or the $crawler data
    }
}

有机会得到这份工作吗?

在此先感谢亨内斯

4

3 回答 3

15

我从未在内存中使用过 sqlite 数据库,但为了测试,我确实使用了保存的 sqlite 数据库。

为此,您应该添加

# app/config/config_test.yml
doctrine:
    dbal:
        default_connection: default
        connections:
            default:
                driver:   pdo_sqlite
                path:     %kernel.cache_dir%/test.db

到您的测试配置(对我来说是 config_test.yml)

您应该能够根据文档将其更改为内存

http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#pdo-sqlite

memory (boolean): 如果 SQLite 数据库应该在内存中(非持久),则为真。与路径互斥。路径优先。

所以配置应该是

# app/config/config_test.yml
doctrine:
    dbal:
        default_connection: default
        connections:
            default:
                driver:   pdo_sqlite
                memory:   true
于 2014-05-08T10:57:59.583 回答
7

接受的答案对我不起作用,因为我使用 URL 来指定连接参数,虽然我将驱动程序设置为pdo_sqlitememorytrue但 Doctrine 仍在使用url根配置中的参数,所以我不得不覆盖它.

#api/config/packages/test/doctrine.yaml
doctrine:
  dbal:
    url: "sqlite:///:memory:"
于 2019-06-15T19:10:49.690 回答
2

您可以轻松地创建自己的 entitymanager 实例。检查这个助手类你可能在 symfony 2 中没有它,但你可以使用这个想法来构建你自己的基础 testCaseClass 并在需要时使用它。这甚至不需要启动内核。

于 2017-06-05T12:13:53.457 回答