Intro

Yii Framwork utilizes the PHPUnit for unit testing and quality assurance. I’m setting up the development environment using Yii for a web application project and following its development methodology.

Yii utilizes the core PHPUnit unit testing functionality and the Selenium extension. PHPUnit is solely for unit testing and I believe Selenium is a functional testing tool/framework for web application (I yet to try). I’m using Mac OS X Snow Leopard.

Install PHPUnit

The following commands are taken from the PHPUnit documentation.

sudo pear config-set auto_discover 1
sudo pear install pear.phpunit.de/PHPUnit

I believe this is enough just to do unit testing. The following two code segments shows a simple test case of project/src/Operations.php and projects/tests/OperationsTest.php:

<?php

/* Operations.php */

class Operations
{
	public static function double($x)
	{
		return $x * 2;
	}
}
?>
<?php

/* OperationTest.php */

require_once("../src/Operations.php");

class OperationsTest extends PHPUnit_Framework_TestCase
{
	function testDouble()
	{
		$this->assertEquals(2, Operations::double(1));
	}
}
?>

Installing Selenium PHPUnit Extension

Testing Framework of Yii references some Selenium extension classes I get erros running Yii test cases with installing Selenium; therefore, I’m certain the extension is required to use Yii’s testing framework. The following command installs the extension:

sudo pear install phpunit/PHPUnit_Selenium

Composing and Running Unit Tests via Yii

The following is a sample class and a sample test class for the class. The class is a very simple Yii controller class and is located at app/protected/controllers/MessageTest.php, and the test is located at app/protected/tests/unit/MessageTest.php.

MessageController.php:

<?php

class MessageController extends Controller
{
	public function repeat($msg)
	{
		return $msg;
	}
}
?>

MessageTest.php:

<?php
Yii::import('application.controllers.MessageController');

class MessageTest extends CTestCase
{
	public function testRepeat()
	{
		$contr = new MessageController('messageTest');
		$msg = 'Hello, anyone out there?';
		$this->assertEquals($msg, $contr->repeat($msg));
	}
}
?>

The following commands run this simple unit test.

cd app/protected/tests
phpunit unit/MessageTest.php