使用 Symfony 测试数据库插入

大家好,

在过去的几天里,我一直在研究测试驱动开发,并决定我也需要学习它.虽然我无法弄清楚如何精确地做到这一点.

I have been looking into Test Driven Development a lot in the past few days and decided that I need to learn it as well. Although I can not figure out how to do it precisely.

我的项目依赖于 Symfony2.1.6 框架和 Doctrine,所以我有一些需要填充的数据库表.

My project depends on the Symfony2.1.6 framework and Doctrine so I have some Database-tables that needs filling.

书籍 (1,n) - (0,n) 类型

Book (1,n) - (0,n) Genre

现在,如果我想插入流派记录,我首先需要编写一个测试以确保所有内容都按应有的方式插入(或者我错了吗?)

Now if I want to insert a Genre-record I first need to write a test to ensure everything is being inserted as it should (or am I wrong?)

现在的问题是我不知道如何访问我的数据库,因为它是由框架管理的.

The problem now is that I dont know how to access my Database as it is managed by the framework.

我唯一能找到的是 LiipFunctionalTestBundlehttps://github.com/liip/LiipFunctionalTestBundle 每次运行测试时都会创建和恢复一个临时数据库.我已经按照说明设置了所有内容.

The only thing I could find was with the LiipFunctionalTestBundle https://github.com/liip/LiipFunctionalTestBundle which creates and restores a temporary database everytime I run a test. I have setup everything according to the Instructions.

我的 app/config/config_test.yml 现在看起来像这样:

My app/config/config_test.yml looks like this now:

imports:
    - { resource: config_dev.yml }

framework:
    test: ~
    session:
        storage_id: session.storage.filesystem

liip_functional_test: ~

web_profiler:
    toolbar: false
    intercept_redirects: false

swiftmailer:
    disable_delivery: true

liip_functional_test:
    cache_sqlite_db: true

doctrine:
    dbal:
        default_connection: default
        connections:
            default:
                driver:   pdo_sqlite
                path:     %kernel.cache_dir%/test.db

所以现在我有一个 GenreTest 类:
Liip 没有文档,所以我只是尝试了这样的方法.

So now I have a GenreTest class:
Liip doesn't have documentation so I just tried an approach like this.

use LiipFunctionalTestBundleTestWebTestCase;
class GenreTest extends WebTestCase {
    public function testInsert() {
        $container = $this->getContainer();
        $registry = $container->get('doctrine');
        $em = $registry->getEntityManager(null);       

        $genre = new Genre();
        $genre->setName("testGenre"); 

        $em->persist($genre);
        $em->flush();

        $result = $em->createQuery("SELECT g FROM QkprodMangressBundle:Genre g ".
                                  "WHERE g.name = :name")
                    ->setParameter("name", $genre->getName())
                    ->getResult();

        $this->assertEqual($result[0]->getName(), $genre->getName());
    }
}

phpunit -c web/

phpunit -c web/

PDOException: 找不到驱动程序/.../Mangress/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:36/.../Mangress/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOSqlite/Driver.php:60/.../Mangress/vendor/doctrine/dbal/lib/Doctrine/DBAL/Connection.php:350/.../Mangress/vendor/doctrine/dbal/lib/Doctrine/DBAL/Connection.php:949/.../Mangress/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:306/.../Mangress/vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php:355/.../Mangress/app/cache/test/jms_diextra/doctrine/EntityManager_510128d0a5878.ph电话:362/.../Mangress/src/Qkprod/MangressBundle/Tests/Entity/GenreTest.php:27失败!测试:3,断言:1,错误:1.

PDOException: could not find driver /.../Mangress/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:36 /.../Mangress/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOSqlite/Driver.php :60 /.../Mangress/vendor/doctrine/dbal/lib/Doctrine/DBAL/Connection.php:350 /.../Mangress/vendor/doctrine/dbal/lib/Doctrine/DBAL/Connection.php:949 /.../Mangress/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:306 /.../Mangress/vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php:355 /.../Mangress/app/cache/test/jms_diextra/doctrine/EntityManager_510128d0a5878.ph p:362 /.../Mangress/src/Qkprod/MangressBundle/Tests/Entity/GenreTest.php:27 FAILURES! Tests: 3, Assertions: 1, Errors: 1.

我遇到的最大问题是.. 我该如何测试这样的东西?或者我什至测试数据库通信?伪造数据库通过自定义实现进行通信似乎不像对我来说是个好主意,因为它将在生产中使用 ORM 和 Doctrine环境也好.

The big question I am having is.. how do I test something like that? Or do I even test database communication? Faking the database communication through a custom implementation doesn't seem like a good idea to me because it will use ORM and Doctrine in the production environment as well.

对不起..这里原来是一本小小说.

Sorry.. turned out to be a little novel here.

推荐答案

我几乎完全通过以下方式解决了我的问题:

I have, almost completely, solved my problem by:

  1. 安装 db-communication 所需的驱动程序 ;)
    PDO_SQLITE 驱动程序不存在.. 怎么办?

sudo apt-get install php5-sqlite

  • 在每次测试运行时重新创建模式
    https://stackoverflow.com/a/10463614/1177024

    <小时>这是我对数据库的班级测试

    namespace QkprodMangressBundleEntity;
    
    use QkprodMangressBundleEntityGenre;
    use SymfonyBundleFrameworkBundleTestWebTestCase;
    
        private $em;
    
        /**
         * Sets up environment for testing
         * Regenerates Database schema before every test-run
         */
        public function setUp() {
            static::$kernel = static::createKernel();
            static::$kernel -> boot();
            $this -> em = static::$kernel->getContainer()
                                         ->get('doctrine')
                                         ->getEntityManager();
            $this->regenerateSchema();
        }
    
        protected function tearDown() {
            parent::tearDown();
            $this -> em -> close();
        }
    
        /**
         * Drops current schema and creates a brand new one
         */
        protected function regenerateSchema() {
            $metadatas = $this->em->getMetadataFactory()->getAllMetadata();
            if (!empty($metadatas)) {
                $tool = new DoctrineORMToolsSchemaTool($this->em);
                $tool -> dropSchema($metadatas);
                $tool -> createSchema($metadatas);
            }
        }
    
    
        public function testInsert() {
            $genre = new Genre();
            $genre -> setName("testGenre");
    
            $this -> em -> persist($genre);
            $this -> em -> flush();
    
            $result = $this -> em 
                        -> createQuery("SELECT g "
                                     . " FROM QkprodMangressBundle:Genre g " 
                                     . " WHERE g.name = :name") 
                        -> setParameter("name", $genre -> getName())
                        -> getResult();
    
            $this -> assertEquals($result[0] -> getName(), $genre -> getName());
        }
    }
    


    无法让 LiipBundle 工作,但您可以通过设置 symfony 将 sqlite db 保存在内存而不是文件系统中来提高速度.https://stackoverflow.com/a/10460139/1177024

    # app/config/config_test
    doctrine:
        dbal:
            driver: pdo_sqlite
            path: :memory:
            memory: true
    


    或者可能只创建一次架构,而不是重新创建它,只需使用新备份覆盖数据库即可.


    Or maybe only create the schema once and instead of recreating it, just override the database with a fresh backup.

    我希望这可以缩短一些有同样问题的人的搜索时间!感谢一路上帮助我的每一个人:)你太棒了!

    I hope this shortens the search for some people having the same problem! Thanks to everyone helping me along the way :) You are great!

  • 相关文章