Generate phpunit fixtures

Last time I had a lot of work and that’s why can’t write something really interesting. So today I decided to write about another one zf command (read how do I do it here Run Zend Framework Command in Yii style) that helps me to build fixtures for PHPUnit.
Imagine you need to quickly create a fixture for some tables with many fields. Writing tests should not be time-consuming. So you do something like this

php script_runner.php createFixtureFromDb --table=user --print=1 --limit=1 --verbose

<?xml version="1.0" encoding="UTF-8"?>
<dataset><tags id="1" login="login" email="" a lot of other fields etc.. />

Shortly how do I do that –


 * Creates fixture for testing from specified DB table
 * @author radzserg
class App_Script_Command_CreateFixtureFromDb extends App_Script_Command_Abstract

    protected $_availableParams = array(
        'table*' => 'Name of the table to import data',
        'file' => 'Path generated xml file. (Either file or print shoud be specified)',
        'print' => 'Output to stdout',
        'limit' => 'limit of rows',
        'rand' => 'if set will add order by RAND()',

    public function execute($params = array())
        if (empty($params['table'])) {
            throw new Exception("Specify source table");
        if (empty($params['file']) && !isset($params['print'])) {
            throw new App_Exception_System("Specify file path for xml");
        $limit = isset($params['limit']) ? (int)$params['limit'] : null;
        $cond = isset($params['cond']) ? $params['cond'] : null;
        $rand = isset($params['rand']) ? true : false;

        $table = $params['table'];
        $filePath = isset($params['file']) ? $params['file'] : null;

        /* @var $adapter Zend_Db_Adapter_Abstract */
        $adapter = Zend_Db_Table::getDefaultAdapter();
        $select = $adapter->select()->from($table);

        if ($rand) {
            $select->order(new Zend_Db_Expr('RAND()'));
        if ($cond) {

        $rows = $adapter->fetchAll($select);

        $doc = new DomDocument('1.0', 'UTF-8');
        $root = $doc->createElement('dataset');
        $root = $doc->appendChild($root);

        foreach ($rows as $row) {
            $xmlRow = $doc->createElement($table);
            foreach ($row as $col => $value) {
                $xmlRow->setAttribute($col, $value);


        $xml = $doc->saveXML();

        if (!isset($params['print'])) {
            file_put_contents($filePath, $xml);
        } else {
            $this->verbose($xml, 'info');


As you can see from $_availableParams help variable we have to set required table param. Other params are optional. You can specify –limit for rows, –file – file path param if you want to save result to file, –print if you want to output result to console, and finally you can specify –rand variable if you want to randomize result.

That’s it, hope it was helpfull.

Leave a Reply

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