PHPUnit in Drupal

PHPUnit was added to Drupal 8 and is the standard for testing Drupal 8+.

It is highly recommended to read the official PHPUnit documentation. In particular, the list of assertions to learn what assertion to use.

It is recommended to write new tests using the PHPUnit base classes UnitTestCase, KernelTestBase, BrowserTestBase (web tests) or WebDriverTestBase (JavaScript-enabled web tests using WebDriver).

We use multiple versions of PHPUnit in DrupalCI on drupal.org. It is discouraged to use end-of-life PHP versions in production (documentation on supported PHP versions).

PHPUnit Browser test tutorial

This tutorial will take you through the basics of PHPUnit Browser testing in Drupal 8+.

PHPUnit JavaScript test writing tutorial

Learn about PHPUnit Javascript testing in Drupal 8+. By the end, you should be able to write your first test.

PHPUnit file structure, namespace, and required metadata

File structure and namespace

Running PHPUnit tests

Execute PHPUnit tests from the command line.

Running PHPUnit JavaScript tests

Learn about how to run PHPUnit JavaScript tests Drupal 8.

Running PHPUnit tests within PhpStorm

Configure PhpStorm to run Drupal's PHPUnit tests.

Understanding PHPunit expectations

A mock object most of the time will contain an expectation like

Unit testing more complicated Drupal classes

Dealing with function calls

Using Prophecy

Mocking with Prophecy in PHPUnit

Comparison with PHPUnit mocks

Now that we saw how you can use prophecy as a start, let's compare it with the other frequently used PHPUnit mocking framework

Agile Unit Testing

What You Should Know

Mocking Entities and Services with PHPUnit and Mocks

Mocking complex entities and services in Unit Tests using PHPUnit mocking framework

Setup tasks in Kernel tests

Setup tasks in Kernel tests

Working with user sessions in tests

How to manipulate and examine user sessions in kernel and functional tests

Making HTTP requests programmatically in Kernel tests

How to use Kernel tests for tests that make simple HTTP requests