【问题标题】:how to assert Yii log messages in a phpunit如何在 phpunit 中断言 Yii 日志消息
【发布时间】:2013-03-14 01:00:42
【问题描述】:

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

【问题讨论】:

  • 您的测试代码示例会有所帮助。
  • 添加示例。谢谢。

标签: php unit-testing yii phpunit


【解决方案1】:

您可能需要创建一个新的自定义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);

我还没有尝试过,但它应该可以正常工作。我喜欢甚至测试错误日志条目的雄心!

【讨论】:

    【解决方案2】:

    有一篇 wiki 文章准确描述了您在此处必须做什么:

    http://www.yiiframework.com/wiki/340/access-log-output-from-unit-tests

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-06
      • 2016-03-05
      • 2018-01-23
      • 1970-01-01
      • 1970-01-01
      • 2017-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多