Mocking your database

October 1, 2008

I think mocking the database in integration tests is a bad idea. It is not a fact, it is my personal opinion. I think that when you are running your integration tests, you should try to mimick the live environment as good as possible. Using a mock to replace your database object doesn’t fit this idea.

If you decide to use the database object you use in your application, you may want to change the actual backend. I use Mysql for different projects, but running integration tests against a mysql test-database is kind of slow. You have to consider filling up you database with a defined dataset (setUp()) for every test and that can take a while. (latest project is about 1sec/test) Instead, you could use an SQLite backend.

Using the SQLite backend is easy when you use a database component that’s worth it. Zend_Db for instance, easily offers you that functionality. By using a different adapter (SQLite instead of MySQLi) you can run your tests a lot faster.

I haven’t found much information about using the SQLite adapter and initializing the database. I guess it all comes down to exporting you MySQL-code to setup you database (DDL) to an SQLite format. Using the XML dataset feature in PHPUnit you can populate that in-memory database and you’re ready to go. Faster.

Leave a Reply