Wednesday, August 13, 2008

CakePHP 1.1 Unit Testing Test Suite v 1.0.0.5 tutorial

So your stuck with CakePHP 1.1, but you need to add Unit Testing, what do you do?


You can grab Cake Test Suite v1.0.0.5 (using SimpleTest) here


The thing with this Test Suite is that I couldn't find documentation anywhere so I decided to write this little tutorial on how to get started.


Step 1: Setup
First make sure your CakePHP Project's debug level is set to at least 1.


Next, after unzipping the app folder into your project and trying to run the test controller(http://yourproject/test/) you might see that you will get this error:


Notice: Use of undefined constant CORE_PATH - assumed 'CORE_PATH' in D:\Flex Workspaces\cakeamfphp\cake\config\paths.php on line 44



To fix this open up /app/webroot/test/index.php and insert this on line 82:

if (!defined('CORE_PATH')) {
if (function_exists('ini_set')) {
ini_set('include_path', CAKE_CORE_INCLUDE_PATH . PATH_SEPARATOR . ROOT . DS . APP_DIR . DS . PATH_SEPARATOR . ini_get('include_path'));
define('APP_PATH', null);
define('CORE_PATH', null);
} else {
define('APP_PATH', ROOT . DS . APP_DIR . DS);
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
}
}

require CORE_PATH.'cake'.DS.'bootstrap.php';


Step 2: Writing the Tests

Lets say for example, I have a model user.php that I want to test, I have to create this file as /app/tests/app/cases/models/User.test.php

It will look something like this:


class UserTest extends UnitTestCase {

function testSomething() {
loadModel('User');
$user = &new User();
$this->assertEqual($user->name, 'User');
}
}

?>



If testing a controller, you would want to use the loadController method.


If I wanted to make a group test of my models I would for example make a file
in app/tests/app/groups/Model.group.php:



require_once(TESTS.'/app/cases/models/User.test.php');
require_once(TESTS.'/app/cases/models/User_Builder.test.php');

class ModelTest extends GroupTest {

function ModelTest(){
$this->addTestCase(new UserTest());
$this->addTestCase(new User_BuilderTest());
}

}

?>





Hope this helps get you on the right track. Take a look at the simpletest docs for more information on how to unit test your project.

No comments: