Skip to content

Database

elblinkin edited this page May 3, 2012 · 4 revisions

This is a tutorial for using https://github.com/etsy/phpunit-extensions/tree/master/PHPUnit/Extensions/Database.

DBUnit was originally written in Java to work with JUnit. It was then ported to PHP as an extension of PHPUnit (as explained in the PHPUnit documentation).

Array Data Set

DBUnit requires that you have some sort of Data Set as a fixture, a base line of data in the database involved in the test. There are several options for Data Sets like CSV, XML, or YAML. These are all fine options but typically result in having external data files lying around. This makes it more difficult to read the test.

In the PHPUnit (DBUnit) documentation has a wonderful suggestion for an Array Data Set. Using such Data Set allows you to list the data you are going to use in the test, with plain-old PHP arrays. No more looking amongst a sea of files to piece together what should be a simple, concise test.

The documentation lists out a possible implementation, but who wants to copy and paste code?

Simply use PHPUnit_Extensions_Database_DataSet_ArrayDataSet like so

    $this->data_set = new PHPUnit_Extensions_Database_DataSet_ArrayDataSet(
        array(
    	'table_a' => array(
    	    array('id' => 1, 'first' => 'bob', 'last' => 'johnson'),
    	    array('id' => 2, 'first' => 'sally', 'last' => 'mae', 'age' => 29),
    	),
    	'table_b' => array(
    		array('id' => 1, 'pet' => 'dog'),
    		array('id' => 2, 'pet' => 'cat'),
    	),
        )
    );
Clone this wiki locally