Symfony 2: how to properly test Doctrine models?

Is there a way to properly unit test Doctrine models in a Symfony 2 application? Right now i'm writing functional tests that go through the controller in order to make sure my application is storing (and CRUDing) data properly. But that takes too long and it's very bad, since i have to setup fixtures for every suite, and clear the database after the suite is finished.

How can i isolate Entity and EntityRepository unit tests? Is there a tutorial available on this?


You shouldn't have any problems with unit testing your entities as long as you keep them decoupled from DB logic.

And here is pretty nice article about testing repositories: https://symfony2-document.readthedocs.org/en/latest/cookbook/testing/doctrine.html.

Moreover you may be interested with this Q&A: Testing Controllers in Symfony2 with Doctrine


We've set-up a singleton called TestManager which sets up an empty test DB once for all tests. Then we truncate just the tables important for a test in the setUp() method and set-up the fixtures in PHP by useing the doctrine API. We use MySql for this.

This gives us a delay of ~10s for every start of phpunit, but this is independant from the number of tests. I think this could be improoved a lot by using the in-memory version of sqlite.

Personaly I learned a lot about setting up functional test with symfony2/doctrine by looking at the the code of Johann Schmitt's functional test for the payment core bundle.

And just to make things clear: If you want to have pure unit test you have to mock doctrine all together. Everything else is a functional / integration test. But often this distingtion is rather academic and it's just to much work to mock doctrine.


A trick that I found which was useful for unit testing is to use sqlite's file based database. You can create your empty database tables in a file called 'emptydatabase.dat' and use sqlite to load it. Now at the end of ever test, you can overwrite the empty database file and start with a fresh database.

You can create empty schema files with this code:

        $classes = array(
            $em->getClassMetadata('MyAPIBundle:Currency'),
            $em->getClassMetadata('MyAPIBundle:Permission'),
            $em->getClassMetadata('MyAPIBundle:Role'),
            $em->getClassMetadata('MyAPIBundle:User'),
        );

        $tool = new DoctrineORMToolsSchemaTool($em);
        $tool->createSchema($classes);
        rename($schemafile, dirname(__FILE__) . '/../Data/schema.dat');

        print "Schema file was regeneratedn";

Also

We also created a service for every major entity that required operations, and easily tested that stand alone service on its own. At first we had everything in the Repository but that didn't make sense, but by moving them to Service and mocking out all the dependent objects things worked out great

链接地址: http://www.djcxy.com/p/68654.html

上一篇: 用godaddy安装ssl证书

下一篇: Symfony 2:如何正确测试Doctrine模型?