Entity view (Content)

Unit and Functional Testing in Drupal

By stran
Oct. 3, 2014

Drupal 7 comes by default with the simpletest (Testing) module which allows you to run test cases against your code, whether it's a small piece of code such as a function, or an entire workflow.

Writing test cases is a good practice for Drupal developers when developing Drupal modules because first of all, it helps in identifying bugs during regression testing. As your application grows more complex over time, new bugs might be introduced, not necessarily from the code, but rather from the change in business logic. Second of all, writing test cases forces you to think outside the box to cover all possible edge cases. Lastly, it might take some time initially to write the test cases but it will save you time in the long run.

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() {
    // 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'));

As you can see, function basically does something, then assert that the result equals something. You can have as many assertions as you want. DrupalWebTestCase does come with a few assert* functions, but you can always define your own assertions if necessary.

That’s it! Now you should be able to go to Configuration | Testing, locate your test cases and run them.

Post Tags: