Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

3 Easy Steps to Drupal Unit Tests

Parent Feed: 

Posted Oct 2, 2012 // 2 comments

While working on the SPS Module we became very well acquainted with Drupal's Unit Test Class. I will have a follow up Post on the lessons we learned about writing test, but here I will outline the basic steps for adding unit test to a module. It is worth noting that I will be talking about the Drupal Unit test not the Drupal Web Test.

Step 1 - Tell Drupal about your tests

Drupal will look for classes that define tests ,so all we need to do is make sure that those classes can be found. To do this we just add a files line to the .info file, so that Drupal knows which files to investigate for test classes.

MODULE.info

1
2
3
  name = MODULE
  core = 7.x
  files[] = tests/*.test

Now we can put all of our tests into the tests folder of the module, as long as we add .test to the file name.

Step 2 - Test Base Class

While a base class is not needed, it can be very helpful, as there are things (such as enabling your module) that can be done in a setup method.
tests/MODULEBase.test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
abstract class MODULEBaseUnitTest extends DrupalUnitTestCase {
  /**
   * One using of this function is to enable the module used for testing, any dependencies
   * or anything else that might be universal for all tests
   */
  public function setUp() {
    parent::setUp();
    //enable module
    $this->enableModule('MODULE');
 
    // enable dep and other thing for all tests
  }
 
  /**
   * Fake enables a module for the purpose of a unit test
   *
   * @param $name
   *  The module's machine name (i.e. ctools not Chaos Tools)
   */
  protected function enableModule($name) {
    $modules = module_list();
    $modules[$name] = $name;
    module_list(TRUE, FALSE, FALSE, $modules);
  }
  ...
}

In the code sample, we simply create a base class that extends DrupalUnitTestCase, and add a setup method, to take care of anything that needs to be done before all of our tests. We also include an enableModule method that fakes enabling a module (the DrupalUnitTestCase, does not have access to a database, so enabling a module the normal way is not available).

Other things we can add to the base case are new methods to support our tests (such as asserts) that one might want to use over and over. For example in SPS module we add an assertThrows, which tests to ensure the correct exception is thrown (note this assert only works in PHP 5.3)
tests/MODULEBase.test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
abstract class MODULEBaseUnitTest extends DrupalUnitTestCase {
  ...
  /**
   * One can also add helper assert functions that might get used in tests
   *
   * This one test if the correct Exceptions is thrown (5.3 only)
   */
  protected function assertThrows(Closure $closure, $type, $error_message = NULL, $message) {
    try {
      $closure();
    }
    catch (Exception $e) {
      if (!($e instanceof $type)) {
        throw $e;
      }
      if (isset($error_message)) {
        if ($e->getMessage() != $error_message) {
          $this->fail($message, "SPS");
          return;
        }
      }
      $this->pass($message, "SPS");
      return;
    }
    $this->fail($message, "SPS");
  }
 
  /**
   * One can also add helper assert functions that might get used in tests
   *
   * Test that an object is an instance of a class
   *
   * @param $class
   * @param $object
   * @param $message
   */
  protected function assertIsInstance($class, $object, $message) {
    if ($object instanceof $class) {
      $this->pass($message, "SPS");
    }
    else {
      $this->fail($message, "SPS");
    }
  }
}

After we have set up our base class, now we can start making our tests.

Step 3 - Write Tests

OK, now we get to write tests! The structure here gets a little bit confusing, one can have as many test classes as one wants, and each test class can have as many test methods, and each test method can have many assertions.

In the SPS module we did a test class for each class provided by the SPS module, with a test method for each method provided by the class and then a test for each method. We found this to be an effective way to structure the test, but there is no required structure.

I also used one file for each test class, each of which extended the base class defined earlier. Each test class should define a getInfo method, to tell us about the test.

The getInfo method returns a array with keys of name, description, and group (I use the module name for this).

1
2
3
4
5
6
7
8
9
10
class MODULETestnameUnitTest extends MODULEBaseUnitTest {
  static function getInfo() {
    return array(
      'name' => 'MODULE Testname ',
      'description' => 'Test the public interface to the Testname of the MODULE module',
      'group' => 'MODULE',
    );
  }
  ...
}

Now for the test methods. Each method that starts with the word 'test' will be run as a test. Each test should include one or more asserts. One can look at the Drupal Unit Test methods to see all of the asserts. AssertTrue and AssertEqual will be the most used asserts.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class MODULETestnameUnitTest extends MODULEBaseUnitTest {
  ...
  /**
   * All test start with test in lowercase letters
   *
   * One can use any of the asserts in this space
   */
  public function testContruction() {
    $value = $this->getCondition('baseball');
    $this->assertIsInstance(
      'MODULECondition',
      $value,
      'Description of what is being checked in this assertion'
 
    $expect = new ModuleCondition('baseball', 'other');
    $this->assertEqual(
      $value,
      $expect,
      'Description of what is being checked in this assertion'
    );
  }
  ...
}

Other methods (those that do not start with 'test') can be used in the test for doing tasks that might be needed by multiple test methods.

1
2
3
4
5
6
7
8
9
10
11
12
class MODULETestnameUnitTest extends MODULEBaseUnitTest {
  ...
  /**
   * Methods that do not start with test, are ignored as test, but can be used for function
   * that might be reused on multiple test.
   */
  protected function getCondition($name) {
 
    return MODULE_get_condition($name, TRUE);
  }
 
}

Running Tests

The last item is to run these tests; that can be done by using the /scripts/run-tests.sh script (this is off of the drupal root). One must have the simpletest module enable to run these tests.

To run only the tests in a specific group (remember I set it to the name of the module earlier) pass the group name as the first argument to the run-tests.sh script.

 php scripts/run-tests.sh GROUPNAME
While one is developing one's tests, or if obe has to drill down on a failing test, one can use the verbose and class flags. This will give a more verbose report on only one class' tests.
 php scripts/run-tests.sh --verbose --class CLASSNAME

One can also use the Testing admin area for running the test (they are grouped by group name), but I find that the script is much more conducive if one is doing Test Driven Development.

When Erik Summerfield joined our software development team, we knew that his natural talents in math and economics would be an asset to our team and clients alike. Plus, his experiences in various programming languages including .NET/C#, perl, ...

Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web