You are here

protected function AssertMailTrait::assertMailString in Drupal 9

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Test/AssertMailTrait.php \Drupal\Core\Test\AssertMailTrait::assertMailString()
  2. 10 core/lib/Drupal/Core/Test/AssertMailTrait.php \Drupal\Core\Test\AssertMailTrait::assertMailString()

Asserts that the most recently sent email message has the string in it.

Parameters

string $field_name: Name of field or message property to assert: subject, body, id, ...

string $string: String to search for.

int $email_depth: Number of emails to search for string, starting with most recent.

string $message: (optional) A message to display with the assertion. Do not translate messages: use \Drupal\Component\Render\FormattableMarkup to embed variables in the message text, not t(). If left blank, a default message will be displayed.

string $group: (optional) The group this message is in, which is displayed in a column in test output. Use 'Debug' to indicate this is debugging output. Do not translate this string. Defaults to 'Other'; most tests do not override this default.

4 calls to AssertMailTrait::assertMailString()
ContactPersonalTest::testSendPersonalContactMessage in core/modules/contact/tests/src/Functional/ContactPersonalTest.php
Tests that mails for contact messages are correctly sent.
RestRegisterUserTest::testRegisterUser in core/modules/user/tests/src/Functional/RestRegisterUserTest.php
Tests that only anonymous users can register users.
UserAdminTest::testUserAdmin in core/modules/user/tests/src/Functional/UserAdminTest.php
Registers a user and deletes it.
UserMailNotifyTest::testUserRecoveryMailLanguage in core/modules/user/tests/src/Kernel/UserMailNotifyTest.php
Tests recovery email content and token langcode is aligned.

File

core/lib/Drupal/Core/Test/AssertMailTrait.php, line 91

Class

AssertMailTrait
Provides methods for testing emails sent during test runs.

Namespace

Drupal\Core\Test

Code

protected function assertMailString($field_name, $string, $email_depth, $message = '', $group = 'Other') {
  $mails = $this
    ->getMails();
  $string_found = FALSE;

  // Cast MarkupInterface objects to string.
  $string = (string) $string;
  for ($i = count($mails) - 1; $i >= count($mails) - $email_depth && $i >= 0; $i--) {
    $mail = $mails[$i];

    // Normalize whitespace, as we don't know what the mail system might have
    // done. Any run of whitespace becomes a single space.
    $normalized_mail = preg_replace('/\\s+/', ' ', $mail[$field_name]);
    $normalized_string = preg_replace('/\\s+/', ' ', $string);
    $string_found = FALSE !== strpos($normalized_mail, $normalized_string);
    if ($string_found) {
      break;
    }
  }
  if (!$message) {
    $message = new FormattableMarkup('Expected text found in @field of email message: "@expected".', [
      '@field' => $field_name,
      '@expected' => $string,
    ]);
  }
  $this
    ->assertTrue($string_found, $message, $group);
}