Yii已建立日志系统。在某些情况下,我想确保正确完成日志记录,即正确的消息被记录为“错误”或“警告”。 如何从phpunit测试用例中读取这些消息?
示例代码:
public function actionDownload($id)
{
$order = self::$dic->get('StoreOrder')->findByPk($id);
$logged = Yii::app()->user->getState('usermodel');
if(!isset($order->id_user))
{
Yii::log("could not get user id from order $id","error");
return false;
}
if(!isset($logged->id_user))
{
Yii::log("could not get user id from from session","error");
return false;
}
# other code...
}
我需要检查在特定测试条件下是否触发了正确的Yii::log
。
答案 0 :(得分:2)
您可能需要创建一个新的自定义CLogRoute
(让我们称之为CTestLogRoute
),这类似于将日志消息推送到内部数组。然后添加一些方法来检索推送到内部数组的最后一条日志消息(让我们称之为getLastLogEntry()
),您可以在assert()
语句中使用它。
您可以将特殊日志路由添加到单元测试config
文件中,如下所示:
'components'=>array(
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CTestLogRoute', // custom log router which will save the messages
'levels'=>'info, error, warning', // select the level you want piped in here
),
),
),
然后在您的单元测试中,您可以执行以下操作:
foreach (Yii::app()->log->routes as $route)
if ($route instanceof CTestLogRoute) // find our log route
$lastLogValue = $route->getLastLogEntry(); // get the last entry
$this->assertEquals('Expected last log value',$lastLogValue);
我没有尝试过,但它应该可以正常工作。我喜欢甚至测试错误日志条目的野心!
答案 1 :(得分:0)
有一篇wiki文章准确描述了你必须要做的事情:
http://www.yiiframework.com/wiki/340/access-log-output-from-unit-tests