Mocking Drupal: Unit Testing in Drupal 8

Experience level
Time slot

Testing provides value by increasing code maintainability, reducing the risk of failure, and increasing confidence in our code. It was often extremely difficult if not impossible to unit test in Drupal 6 and Drupal 7 because of the dependence of state throughout core, and this led to a reliance on SimpleTest functional testing. However we can now add fast unit tests to compliment our functional, behavioral and manual testing in Drupal 8 by using PHPUnit in our modules.

Drupal is complex. This is not a simple web application. There are over tens of thousands of assertions in Drupal core alone.

I will talk about how we can focus on unit testing our own custom code in Drupal 8 going over several topics:

  • Getting started with PHPUnit and Drupal 8.
  • Deciding what is important to test and how to mock what is not important.
  • Leveraging coverage analysis to improve your code.
  • Using automated testing systems such as TravisCI or DrupalCI.