![]() |
|
Snippets |
|
Even though the book is quite good, the part in which unit testing is explained could use some better information. Especially the testing with a database connection (Propel in this case) needs some fixing.
Below you find an example unit test in which the database is accessed.
It tests a fictional class 'testClass' with the method 'load()'. That method accesses the database ... for which Propel needs to be running. The Symfony application that is loaded is called 'myapp';
if (!@constant('SF_APP')) { // Only load constants in not done before (group tests) define('SF_APP', 'myapp'); define('SF_ENVIRONMENT', 'dev'); define('SF_DEBUG', TRUE); } if (!@constant('SF_ROOT_DIR')) { // Only load constants in not done before (group tests) include(dirname(__FILE__).'/../bootstrap/unit.php'); } sfCore::initSimpleAutoload(array(SF_ROOT_DIR.'/lib/model' // DB model classes ,$sf_symfony_lib_dir // Symfony itself ,dirname(__FILE__).'/../../lib' // Location class to be tested ,dirname(__FILE__).'/../../apps/stageselect/lib' // Location myapp application ,SF_ROOT_DIR.'/plugins')); // Location plugins set_include_path($sf_symfony_lib_dir . '/vendor' . PATH_SEPARATOR . SF_ROOT_DIR . PATH_SEPARATOR . get_include_path()); /* * Start database connection and Symfony core */ sfCore::bootstrap($sf_symfony_lib_dir, $sf_symfony_data_dir); sfContext::getInstance(); Propel::setConfiguration(sfPropelDatabase::getConfiguration()); Propel::initialize(); /* * Test */ // Init $oTest = new lime_test(1, new lime_output_color()); // Print head $oTest->diag('testClass'); $oTest->diag('----'); // Does the method load() exist in class 'testClass' $oTest->can_ok('testClass', 'load', 'testClass has method load()');
Comments on this snippet
Your mileage may vary - I found the following worked better for me:
<pre class="php"> <?php if (!@constant('SF_APP')) { // Only load constants in not done before (group tests) define('SF_APP', 'admin'); define('SF_ENVIRONMENT', 'dev'); define('SF_DEBUG', TRUE); }
$sfRootDir = realpath(dirname(FILE).'/../..'); require_once($sfRootDir.'/test/bootstrap/unit.php');
sfCore::initSimpleAutoload(array( $sfRootDir.'/lib', // DB model classes $sf_symfony_lib_dir, // Symfony itself $sfRootDir.'/apps/'.SF_APP.'/lib', // Location myapp application $sfRootDir.'/plugins')); // Location plugins
set_include_path($sf_symfony_lib_dir . '/vendor/' . SF_ROOT_DIR . '/' . get_include_path());
/* * Start database connection and Symfony core */ sfCore::bootstrap($sf_symfony_lib_dir, $sf_symfony_data_dir); sfContext::getInstance(); Propel::setConfiguration(sfPropelDatabase::getConfiguration()); Propel::initialize();
$t = new lime_test(1, new lime_output_color());
$u = sfGuardUserPeer::retrieveByUsername('admin'); $t->is( $u->getUsername(), 'admin', 'getUsername returns "admin"'); </pre>
(Aside: note there's no need to use PATH_SEPARATOR if you use forward slash - it's Posix!)