Yii unit test for the console command

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:

class HrmCommandTest extends CTestCase
 public function setUp()
      $CCRunner=new CConsoleCommandRunner();
      $this->api = new HrmCommand($commandName,$CCRunner);
 public function tearDown()
 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:



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