Practices for database testing in Symfony2? How to isolate?

前端 未结 4 1878
别那么骄傲
别那么骄傲 2021-02-13 19:42

What are the current best practices for testing database interaction with Symfony2? I have a simple CRUD setup and i want to make sure my testing is OK. Right now, i have 4 test

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-13 20:09

    The question is pretty old but still valid today so here is my experience and how I handle it today on my Symfony projects.

    I started of using an SQLite in-memory database for my tests and I rebuild the db schema + inserted fixtures before each single test case. This had two major drawbacks:

    • It was still way too slow :(
    • On dev & prod I used Mysql which soon became a problem because SQLite simply does not have all the features needed and sometimes behaves differently

    Using MSQL for the tests and rebuilding the schema + inserting fixtures before each test was simply too slow. So I was looking for alternatives...

    I stumbled across this blog post: http://alexandre-salome.fr/blog/Symfony2-Isolation-Of-Tests

    The guy here suggests to run tests inside active database transactions and simply roll back any changes after every single test.

    I took this idea and created a bundle for it: https://github.com/dmaicher/doctrine-test-bundle

    The setup of the bundle is really easy and does not require changing any existing php test classes. Internally it changes the doctrine config to use custom database connections + driver.

    With this bundle you can simply create your database schema + insert fixtures ONCE BEFORE running the whole testsuite (I prefer doing this in a custom phpunit bootstrap file). Using the phpunit listener all tests will run inside database transactions.

    I've been using this bundle since a while already and for me it works out perfectly using SQLite, MySQL or PostgreSQL.

    Since a while its also used on the symfony-demo project.

提交回复
热议问题