Implement a Unit Test in Drupal for Drupal 8, Drupal 9

Last updated June 15, 2020
Module Development8.9.x/9.3.x

Let's write somewhat strict unit tests in a Drupal module. By the end of this tutorial, you will be able to:

  • Understand what makes a unit test different from other types of tests.
  • Determine the specifications of a unit test.
  • Use mocking to isolate units under test, and to force code flow to achieve high coverage.

We'll start out with a brief introduction to unit tests. Then we'll look at a contrived example of a Drupal controller class for illustration purposes. Next, we'll test two units of this controller class, each requiring different mock styles.