Check your version

This video covers a topic in Drupal 7 which may or may not be the version you're using. We're keeping this tutorial online as a courtesy to users of Drupal 7, but we consider it archived.

Alternate resources: 

Writing Unit Tests Using DrupalUnitTestCase

Video loading...

Join Drupalize.Me to watch this video

Join today and gain instant access to our entire video library.

Log in Sign up
  • 0:03
    Writing Unit Tests Using DrupalUnitTestCase
  • 0:05
    with Joe Shindelar
  • 0:08
    So far, all of the tests we've written have been
  • 0:10
    functional tests, which makes sense, because the majority
  • 0:14
    of tests in Drupal 7 are functional.
  • 0:17
    However, SimpleTest provides the ability to write unit tests as
  • 0:20
    well, and Drupal 8 is moving in that direction
  • 0:23
    of more and more unit tests.
  • 0:25
    So it's a good idea to take a look at how they work.
  • 0:29
    Earlier in this series, we said that unit tests are tests that operate

Writing Unit Tests Using DrupalUnitTestCase

Loading...

Due to the tightly coupled nature of much of Drupal 7's code most of the test suite is based around functional tests and not unit tests. However, there are a handful of unit tests in core as well as the DrupalUnitTestCase class that we can extend to write our own unit tests. Since unit tests are an important part of a complete test suite lets take a look at how we can extend the DrupalUnitTestCase class and add some unit tests to our module. While functional tests do a good job of telling us that something is broken and we should fix it they often are not very helpful for locating the exact problem. Unit tests on the other hand are much more specific and can generally tell us both that something is wrong, and what is wrong.

Unit tests don't have access to the database or the file system since they are not run in the context of a fully bootstrapped Drupal environment. Note that calling any Drupal functions which attempt to access the database will result in an exception being thrown and cause your tests to fail. This includes functions like watchdog(), and module_implements(). However, because Drupal doesn't have to be bootstrapped, and we don't have to create an entirely new environment, unit tests are a whole lot faster to execute than functional tests.

In this lesson we're going to take a look at writing a unit test for a function in our module that is used to convert a length of time in seconds to a string like 1 hour 6 minutes. We'll start by looking at the code that does the conversion, and then come up with a list of known inputs and their expected outputs. Finally, we'll write a unit test by adding a new .test file that contains our unit tests and bombarding our conversion function to make sure it's working properly.

Downloads: 
Log in or sign up to download companion files.
Additional resources: