thevikas
thevikas

Reputation: 1639

how to assert Yii log messages in a phpunit

Yii has logging system built. In certain case I want to make sure that logging is done properly, i.e. correct message is getting logged as "error" or "warning". How can I read these messages from phpunit test case?

Example Code:

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...
}

I need to check that correct Yii::log was fired in particular test condition.

Upvotes: 2

Views: 816

Answers (2)

Michael Härtl
Michael Härtl

Reputation: 8607

There's a wiki article which describes exactly what you have to do here:

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

Upvotes: 0

thaddeusmt
thaddeusmt

Reputation: 15600

You'll probably need to create a new custom CLogRoute (let's call it CTestLogRoute), which does something like push log messages to an internal array. Then add some methods to retrieve the last log message pushed to the internal array (let's call it getLastLogEntry()), which you can use in your assert() statement.

You can add the special log route to your unit test config file like so:

'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
       ),
    ),
 ),

Then in your unit test you can do something like this:

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);

I haven't tried it, but it should work just fine. I like the ambition of even testing the error log entries!

Upvotes: 2

Related Questions