Loading MySQL data for phpunit testing

I’d been bugged for a while because when I was writing phpunit tests for some of my code, I couldn’t find a tidy way of pre-loading data into a MySQL database for testing against. Everything I came up with seemed really kludgy and the documentation hadn’t really enlightened me much.

Eventually I resorted to reading the code for phpunit and discovered that it can load a database from an XML dump, which can be created directly from mysqldump. This means that if I have a database containing a large amount of static data that I need to test against I can first do:

mysqldump --xml ... > test-data.xml

and as long as the database is created my phpunit test classes just start as follows:


require_once 'PHPUnit/Extensions/Database/TestCase.php';

class ExampleTest extends PHPUnit_Extensions_Database_TestCase
  protected function
    try {
      $pdo = new PDO('mysql:host='.DBHOST.';dbname='.DBNAME, DBUSER,
          DBPASS );
    } catch ( PDOException $e ) {
      throw ( new Exception ( $e->getMessage()));
    return $this->createDefaultDBConnection( $pdo, DBNAME );

  protected function getDataSet()
    return $this->createMySQLXMLDataSet(
        dirname(__FILE__).'/test-data.xml' );

  // test case functions follow

which is far neater than the previous mess I was using to initialise the database.

This entry was posted in Computing and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *