Database Testing with PHPUnit and MySQL
I recently made a contribution to the PHPUnit project that I thought I'd take a blog post to discuss. One of the extensions bundled with PHPUnit adds support for database testing. This extension was contributed by Mike Lively and is a port of the DbUnit extension for the JUnit Java unit testing framework. If you're interested in learning more about database unit testing, check out this presentation by Sebastian Bergmann on the subject.
One of the major components of both extensions is the data set. Database unit tests involve loading a seed data set into a database, executing code that performs an operation on that data set such as deleting a record, and then checking the state of the data set to confirm that the operation had the desired effect. DbUnit supports multiple formats for seed data sets. The PHPUnit Database extension includes support for DbUnit's XML and flat XML formats plus CSV format as well.
If you're using MySQL as your database, CSV has been the only format supported by both the mysqldump utility and the PHPUnit Database extension up to this point. My contribution adds support for its XML format to the extension. While this support was developed to work in the PHPUnit 3.4.x branch, it won't be available in a stable release until 3.5.0. In the meantime, this is how you can use it now.
-
Go to the commit on Github and apply the additions and modifications included in it to your PHPUnit installation.
-
From a shell, get your XML seed data set and store it in a location accessible to your unit test cases.
mysqldump --xml -t -u username -p database > seed.xml
-
Create a test case class that extends
PHPUnit_Extensions_Database_TestCase
. ImplementgetConnection()
andgetDataSet()
as per the documentation where the latter will include a method call to create the data set from the XML file as shown below.$dataSet = $this->createMySQLXMLDataSet('/path/to/seed.xml');
-
At this point, you can execute operations on the database to get it to its expected state following a test, produce an XML dump of the database in that state, and then compare that dump to the actual database contents in a test method to confirm that the two are equal.
$expected = $this->createMySQLXMLDataSet('/path/to/expected.xml'); // Specify a SELECT query as the 2nd parameter here to limit the data set, // else the entire table is used $actual = new PHPUnit_Extension_Database_DataSet_QueryDataSet($this->getConnection()); $actual->addTable('tablename'); $this->assertDataSetsEqual($expected, $actual);
That's it! Hopefully this proves useful to someone else.
Update #1 2012/01/15: I finally got around to submitting a patch to document this feature in the PHPUnit manual. Sebastian has merged it, so it will hopefully be available in the online manual soon.
Update #2 2012/01/23: I got around to checking the online version of the manual and the current build includes my patch. Enjoy.