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
- When the assertion in inside a loop.
- In a custom assertion method in a trait or base test class. A custom assertion method begins with
public function assert*();. - 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:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion
Still on Drupal 7? Security support for Drupal 7 ended on 5 January 2025. Please visit our Drupal 7 End of Life resources page to review all of your options.