Jeb Wilkins

Coding and climbing in Cumbria.

PHP Data Factory

I’ve recently written a super simple Data Factory for PHP, called FactoryLib. This can be used to create test data when unit testing your PHP code.

Including this in your tests is very simple

require 'factory_lib.php' ;
Factory::$factory_data['my_table_name'] = array('name' => 'Jeb Wilkins', 'age' => '101') ;

There are two static methods which can be used to create data

  • Create - predictably used to create rows - Factory::create(‘my_other_table’)

  • Hash - returns an associative array of the data that would otherwise have been inserted - Factory::hash(‘my_table_name’)

Column values can be overridden from the defaults by supplying and array of overriding values as the second parameter, eg

Factory::create('my_table_name', array('name' => 'Alter Ego')) ;

Dynamic Definitions

You can also generate differing string data dynamically using the magic string so

Factory::$factory_data['some_table'] = array('name' => 'Test User ', 'age' => 17)) ;

for($i = 10; $i < 0; $i++)
  Factory::create('some_table') ;

would create 10 users name ‘Test User 1’ through to ‘Test User 10’. To reset the counter use either Factory::reset_counter() to reset the counter for all tables, or Factory::reset_counter(‘my_table_name’) to just reset the counter for a specific table name.

To use this in your code you can do something like the following

require_once 'PHPUnit/Framework.php' ;
require_once 'factory_lib.php' ;

$GLOBALS['show_db_errors'] = true ; // causes factory lib to output errors if something goes wrong

mysql_connect() ; //may need some connection parameters depending upon your setup
mysql_select_db('my_test_db') ; // You do _not_ want this to be your development (or production) database

Factory::$factory_data['person'] = array('name' => 'Test User ', 'address1' => 'First Line of Address') ;

class personTest extends PHPUnit_Framework_TestCase {

  function setUp() {
    Factory::truncate('person') ; // function not implemented yet but will be shortly
  }

  function testCountingUsers() {
    for($i = 0; $i < 5; $i++)
       Factory::create('person') ;

    $this->assertEquals(5, MyPersonClass::countAllPeople()) ;
  }
}

Get the code from GitHub