Code Snippets

Drupal 7 Testing

Drupal 7 includes a testing module for screening applications. This contains a step by step process of using it. For further information refer to this blog post.

All test cases should go in a .test file. So if your module is called mymodule, then create a mymodule.test file under your mymodule directory.

Next, we make sure the file is included by adding it to your .info file

files[] = mymodule.test

Now create a class that extends the DrupalWebTestCase class

class MymoduleTestCase extends DrupalWebTestCase {
}

Now create a getInfo() to tell simpletest about our test case

public function getInfo() {
    return array(
        'name' => 'Our test case',
        'description' => 'Our test case description',
        'group' => 'Our group',
    );
}

This information is to allow us to locate our test case in the simpletest interface. The ‘group’ parameter is used to group similar test cases together.

Next is the setUp() function.  This is where do we our initial set up for whatever we might need during the tests.

function setUp() {
    parent::setUp();
    // more set up code if needed
}

If there are any modules that need to be loaded for this test, you can pass them in 

parent::setup(‘module1’, ‘module2’, ‘etc’);

Now we are ready to write test cases. Test case function names should begin with the word ‘test’ followed by a descriptive text of what you are testing. For example, testCommentPreview(), testCommentOrdering(), testThreadedCommentView(), etc

function testWhatIsTheMeaningOfLife(){
    $data = what_is_the_meaning_of_life();
    $this->assertEqual(42, $data, t('The what_is_the_meaning_of_life function returns 42'));
}

Resource Tags: