Yii unit test for the console command

Posted: June 10, 2015 in Php, PhpUnit, Unit Testing, Yii Framework
Tags: ,

So you want to test your console command with PHPUnit..lets rock!

Let say i have this file MyCompareCommand.php in my commands folder:

class MyCompareCommand extends CConsoleCommand
{
public function compareMonth($currentDate, $compareWithDate, $selectedPeriod=3)
{
 $arrMonth = array(3, 6, 9, 12, 15);
 foreach($arrMonth as $val){
    if($val >= $selectedPeriod){
        $nextDate = JDateTime::getNextMonth($currentDate, $val);
        if($nextDate == $compareWithDate){
              return $val . ' months';
        }
     }
 }
 return false;
}

Then in my tests/unit folder, i’ll have MyCompareCommandTest.php with below code:

<?php
Yii::import('application.commands.*');
class HrmCommandTest extends CTestCase
{
 public function setUp()
 { 
      $commandName='MyTest';
      $CCRunner=new CConsoleCommandRunner();
      $this->api = new HrmCommand($commandName,$CCRunner);
 }
 
 public function tearDown()
 { 
      unset($this->api); 
 }
 
 public function testCompareMonth()
 {
 $this->assertEquals('3 months', $this->api->compareMonth('2015-03-08', '2015-06-08', 3));
 }
 
}

So run from your command line something like this

user@ubuntu:tests# ../../bin/phpunit unit/MyCompareCommandTest.php

 

Source Reference and thanks to Antonis:

http://www.yiiframework.com/forum/index.php/topic/29569-unit-testing-shell-cconsolecommands/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s