Drupal Test coding standards

Last updated on
16 June 2025

Assertion messages

PHPUnit assertion methods provide an optional $message parameter that can override the message provided about the assertion in the test output. For example, the function signature of assertTrue() is:

assertTrue(bool $condition, string $message = "");

Most test assertions should not add custom assertion messages

The default assertion message provided by PHPUnit should be used in most situations. Custom messages add unnecessary bloat, and in practice they often mislead the developer. It is therefore Drupal core's policy to not use the optional $message parameter in most cases. Core merge requests containing use of custom test assertion messages will usually be marked Needs work.

The following section explains when a custom assertion message can be added and the format the message should take.

When to add a custom assertion message

  1. When the assertion in inside a loop.
  2. In a custom assertion method in a trait or base test class. A custom assertion method begins with public function assert*();.
  3. In a helper method.

Format of a custom assertion message

%subject% should %verb% %payload%

Definitions

%subject%
The additional context information
%verb%
The action.
%payload%
The value the %subject% should be.

Example

foreach ($expected_steps as $element_id => $step_value) {
  foreach (['s', 'i', 'h', 'd', 'm', 'y'] as $sub_field) {
    $name = $element_id . '[' . $sub_field . ']';
    $expected_step = $step_value[$sub_field] ?? 1;
    $input = $this->xpath("//form//input[@name='$name']");
    $this->assertCount(1, $input, "Duration input $name should appear exactly once.");
    $actual_step = (integer) $input[0]->attributes()->{'step'};
    $this->assertEquals($expected_step, $actual_step, "Duration input $name should have the correct step value.");
  }
}

  where

{subject} == "Duration input $name"
should == 'should' ;)
{verb} == 'have'
{payload} == 'the correct step value'

Help improve this page

Page status: No known problems

You can: