symfony – 単体テストで propel を使う方法

機能テスト(functional test) やバッチスクリプト(batch)で Propel を使う方法については以前こちらの記事

sfContext::getInstance();

を最初に実行すれば動作する、と書きました。
 
しかし単体テストで Propel を使う際は、単純に

require_once(dirname(__FILE__).’/../bootstrap/unit.php’);
sfContext::getInstance();

とするだけでは

Fatal error: Class ‘sfContext’ not found in …

のように、sfContext クラスが見付からずエラーになります。
ここで単純に sfContext を include しても、sfCore や myUser などが存在しないと言われたり、様々なエラーがでて動作しません。
前述の記事の参考URLにあるように、次のようなコードが必要になります(注: 参考元の投稿コードから僅かに手を加えています)。

// TODO: 要変更 – テスト対象のアプリケーション名
$app_name = “frontend”;
 
//begin initialise database code
include(dirname(__FILE__).’/../bootstrap/unit.php’);
include(dirname(__FILE__).’/../../config/config.php’);

require_once($sf_symfony_lib_dir.’/util/sfCore.class.php’);
sfCore::initSimpleAutoload(array(SF_ROOT_DIR.’/lib/model’ // DB model classes
                                ,$sf_symfony_lib_dir // Symfony itself
                                ,dirname(__FILE__).’/../../apps/stageselect/lib’ // Location app lib
                                ,SF_ROOT_DIR.’/plugins’)); // Location plugins
set_include_path($sf_symfony_lib_dir . ‘/vendor’ . PATH_SEPARATOR . SF_ROOT_DIR . PATH_SEPARATOR . get_include_path());
 
define(‘SF_ENVIRONMENT’, ‘test’);
define(‘SF_APP’, $app_name);
define(‘SF_DEBUG’, true);
 
sfCore::bootstrap($sf_symfony_lib_dir, $sf_symfony_data_dir);
sfContext::getInstance();
Propel::setConfiguration(sfPropelDatabase::getConfiguration());
Propel::initialize();
// end initialise database code
 
// 初期化終わり、以下テストコードが続く…
 
$lime = new lime_test();
 
// :

 
原因についてはエラーや対策のコードを見れば想像がつくと思いますが、単体テストでは機能テストと違い bootstrap (unit.php, functional.php)を include するだけで symfony プロジェクトをまるごと読み込んだり初期化しないようになっているためです。