test.ical.ly | getting the web by the balls



Options for setting up a Doctrine database connection when PHPUnit testing symfony plugins

It is rarely the case that your unit tests actually test your database. It is however not so rare that the code your unit test tries to cover needs a database connection of some sorts.

In symfony 1.x you will find quite some tightly coupled code. Together with Doctrines (1.x) implementation of the active record pattern you will get a lot of exceptions complaining about no open database connection.

So if your tests need a database connection how should you do that?

I created a little experiment to test setting up database connections. If you’re interested you can reproduce those experiments with the sources on GitHub.

I basically tried a few combinations of the following code.

Setting up a database connection using the settings in the fixture projects databases.yml

Setting up a database connection using Doctrines mock adapter


You should always set up a database connection using the setUp() method of your testcase or a test method itself if it is the only method requiring a database connection. This way you only use the database when you actually need it.

I am still pretty amazed that using the mock adapter shows no functional difference to sqlite::memory: and is using up the same amount of memory.

Using –process-isolation on PHPUnit when executing a testcase or testsuite will drastically reduce the memory consumption but at the time of writing this (using PHPUnit 3.5RC1) it will produce a strange runtime exception when the database connection is made in the bootstrap file.

Oh and on the GitHub page you can also see the results of the experiments. :)

· · · · · · ·

  • You can also do it by skipping any symfony specific code, depending on what you are unit testing this may be an advantage (e.g. if you are just testing table queries). Crossing my fingers that this code displays correctly:

    $this->dbManager = Doctrine_Manager::getInstance();
    $this->$dbManager->openConnection(‘sqlite::memory:’, ‘doctrine’);
    $modelsDirpath = dirname(__FILE__) . ‘/path/to/models’;

  • @Daniel thanks for the tip!



Theme Design by devolux.nh2.me