While the above example works great for conveniently regenerating the database structure, chances are you're going to additionally want to initialize some test data. Unfortunately, the Doctrine 2 release is no longer packaged with the convenient
YAML-related features available in the 1.X releases, meaning another solution must be devised. Fortunately, PHPUnit's
DBUnit extension takes much of the pain out of devising your own custom solution.
The following code isn't ideal because in order to demonstrate the core feature of DBUnit I'll need to duplicate a bit of database connection credentials which would otherwise be retrieved directly from the
application.ini file (see the article
Introducing the Zend Framework's Application Configuration Component for more information about accessing configuration data), it should nonetheless provide you with a sound understanding of DBUnit's capabilities. In order to use DBUnit, you'll need to make a few minor but important changes to your project's base test class. The modified code is presented next. Notice in particular how the base class now extends
PHPUnit_Extensions_Database_TestCase, and that two additional required methods have been defined, namely
getConnection() and
getDataSet(). The former method is responsible for establishing the database connection, while the latter is responsible for loading the data set into the database:
Doctrine 2 developer Benjamin Eberlei released
DoctrineExtensions, which includes a PHP Unit Extension for Doctrine. By the looks of it (see the documentation available via the previous link), it's possible to remove the redundant authentication credentials and instead refer to the Doctrine entity manager. Stay tuned as in an upcoming article I'll introduce the DoctrineExtensions project in some detail.
Of course, interacting with the database in the fashion described above is a pretty expensive process. In fact, when you're merely interested in testing the classes which interact with a data source, consider using
test doubles (stubs and mocks), a feature I'll discuss in an upcoming installment.
Jason Gilmore is founder of the publishing, training, and consulting firm
WJGilmore.com. He is the author of several popular books
"Easy PHP Websites with the Zend Framework",
"Easy PayPal with PHP", and
"Beginning PHP and MySQL, Fourth Edition". Follow him on Twitter at
@wjgilmore.