Using PHPUnit or PHPSpec when developing Drupal modules has some obvious benefits; you don’t have to reload you entire website in a browser each time you want to test your module.I have spent the last couple of months developing modules for Drupal 5 and 6 and I tend to spent too much time clearing the cache and the theme registry when using the hook_menu (). The problem is that you need to tell Drupal about the new menu item before you can call it, even in a test case.
If you want to use PHPUnit when developing Drupal modules, and if you want to have a folder structure where tests are not stored together with you actual modules – tests do not belong in any production environment – this guide will be helpful.
To make unit testing agnostic in Drupal you need to store your tests at the root level of your Drupal directory, I prefer this structure for my Drupal projects:
Notice the “tests” folder in the root, that’s where all our PHPUnit tests will go.
To get this running you will need to include Drupal’s bootstrap inside your PHPUnit test case, and you can use the following set_include_path script:
define('ROOT_PATH', realpath(dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR)); set_include_path(ROOT_PATH . PATH_SEPARATOR . get_include_path() );
Now you can safely include the bootstrap.inc file located inside the includes folder in your root directory like so:
include_once 'includes' . DIRECTORY_SEPARATOR . 'bootstrap.inc';
and once that’s done, you can bootstrap the testcase:
That’s it, now your ready to use PHPUnit when developing Drupal modules, and to do so, cd into your root directory and execute the following PHPUnit code:
phpunit ModuleTest tests/ModuleTest.php
That’s it, enjoy.