Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 861
vinnylinux Avatar asked Jan 22 '13 00:01

vinnylinux


2 Answers

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

like image 155
Cyprian Avatar answered Nov 10 '22 12:11

Cyprian


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.

like image 20
BetaRide Avatar answered Nov 10 '22 13:11

BetaRide