SimpleTest tips

Enough ranting about testing, here are some useful tips for enjoying SimpleTest.

Getting Rolling
If this is your first time, start by downloading the SimpleTest module, and the Simple Test framework. Then create a directory in your module called tests, and add a file your_module.test. Here is a template:

<?php
class YourModuleTest extends DrupalTestCase {
  function
get_info() {
    return array(
'name' => t('Your Module Test'),
    
'desc' => t('blah, blah'),
    
'group' => 'Your Tests');
  }
  function
setUp() {
   
// do any set up
 
}
  function
testRawFragment() {
    
// get rolling with $this->asserts
 
}
?>

Then add this to your module:

<?php
function your_module_simpletest() {
 
$dir = drupal_get_path('module', 'your_module'). DIRECTORY_SEPARATOR . 'tests';
 
$tests = file_scan_directory($dir, '\.test');
  return
array_keys($tests);
}
?>

There are other ways to do it, but this will get you up and running.

Custom Path
I like functionality of the SimpleTest but I don’t care for the interface. So I just create a custom drupal path to run my tests directly:

<?php
function your_module_menu($may_cache) {
  if(
$may_cache) {
   
$items[] = array('path' => 'your_module/test',
     
'callback' => 'your_module_test',
     
'access' => true,
     
'type' => MENU_CALLBACK);
  }
  return
$items;
}

function your_module_test() {
 
simpletest_load();
 
$output = simpletest_run_tests( array( 'YourModuleTest' ) );
  print
theme('page', $output);   
}
?>

Validating HTML Fragments
Saving the best for last. I am currently working on code that generates html fragments. Simple Test out-of-the-box does a great job helping you test entire http pages, but only it if goes and gets them itself. I could not find any easy way to load in a local page/fragment. So I did it the hard way:

<?php
 
function setUp() {
    require_once(
SIMPLE_TEST . '/mock_objects.php');
   
Mock::generate( 'SimpleHttpResponse' );
  }

  function setSource( $html ) {
   
$this->_mockResponse = new MockSimpleHttpResponse();
   
$this->_mockResponse->setReturnValue( 'isError', false ); 
   
$this->_mockResponse->setReturnValue( 'getContent', $html );
   
$this->_browser->_page = $this->_browser->_parse( $this->_mockResponse );
  }
?>

Now, in my tests, I can say great things like this:

<?php
    $html
= drupal_get_form( $form_id );
   
$this->assertNull( form_get_errors() );
   
$this->setSource( $html );
   
$this->assertText( 'bar' );
   
$this->assertField( 'setme', 'one');
   
$this->assertNull( $this->_browser->getField('added') );
?>