代碼若不整潔,只會越來越糟糕;代碼寫不好,公司要黃是遲早。
Yii 的應用有兩種,下面記錄這兩種應用的單元測試方法
- webApplication
- consoleApplication
在protected\tests下面放 bootstrap.php
<?php
date_default_timezone_set("Asia/Shanghai");
// change the following paths if necessary
$_SERVER['DOCUMENT_ROOT'] = dirname(__FILE__) . '/../';
set_include_path($_SERVER['DOCUMENT_ROOT']);
error_reporting(E_ALL);
defined('YII_DEBUG') or define('YII_DEBUG',true);
// change the following paths if necessary
$yii=dirname(__FILE__).'/../../../framework/yii.php';
$config=dirname(__FILE__).'/../../protected/config/main.php';
$console=dirname(__FILE__).'/../../protected/config/console.php';
// specify how many levels of call stack should be shown in each log message
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',3);
require_once($yii);
//require_once($config);
//require_once($console);
Yii::setPathOfAlias('application', $_SERVER['DOCUMENT_ROOT']);
Yii::import("application.components.*");
Yii::import('application.extensions.a.*');
Yii::import('application.extensions.b.*');
Yii::import('application.extensions.c.*');
Yii::import('application.extensions.d.*');
Yii::import('application.extensions.e.*');
Yii::import('application.extensions.f.*');
Yii::import('application.extensions.g.*');
Yii::import("application.services.*");
Yii::createWebApplication($config);
//Yii::createConsoleApplication($console);
研究一下午,PHP 的include 真的複雜,import 非常important,有了Bootstrap.php
在tests下面的測試文件例如 ServicesTester.php
第一行寫
require_once ("../bootstrap.php");
然後就寫MockClass 和 TestCase 就好了。
注意:
bootstrap 最後的兩行,差別在於讀取的配置文件不同,可能導致數據庫連接配置的問題。
命令行的項目 讀的是console.php。
Web項目讀的是main.php。
Yii:app()->db 讀的位置取決於 讀的配置文件,這一點容易出錯。