View source
<?php
namespace Drupal\KernelTests\Core\Test;
use Drupal\Core\Test\AssertMailTrait;
use Drupal\KernelTests\KernelTestBase;
class AssertMailTraitTest extends KernelTestBase {
use AssertMailTrait;
public function testAssertMailTrait() {
$mail_service = \Drupal::service('plugin.manager.mail');
$subject = $this
->randomString(64);
$body = $this
->randomString(128);
$message = [
'id' => 'drupal_mail_test',
'headers' => [
'Content-type' => 'text/html',
],
'subject' => $subject,
'to' => 'foobar@example.com',
'body' => $body,
];
$captured_emails = $this
->getMails();
$this
->assertCount(0, $captured_emails, 'The captured emails queue is empty.');
$mail_service
->getInstance([
'module' => 'simpletest',
'key' => 'drupal_mail_test',
])
->mail($message);
$captured_emails = $this
->getMails();
$this
->assertCount(1, $captured_emails, 'One email was captured.');
$this
->assertMailPattern('id', $message['id']);
$this
->assertMailPattern('subject', "^.{64}\$");
$this
->assertMailPattern('to', "[a-z]{6}@example\\.com\$");
$this
->assertMailPattern('body', "^.{128}\$");
foreach ($message as $field => $value) {
$this
->assertMail($field, $value, "The email was sent and the value for property {$field} is intact.");
}
for ($index = 0; $index < 5; $index++) {
$message = [
'id' => 'drupal_mail_test_' . $index,
'headers' => [
'Content-type' => 'text/html',
],
'subject' => $this
->randomString(64),
'to' => $this
->randomMachineName(32) . '@example.com',
'body' => $this
->randomString(512),
];
$mail_service
->getInstance([
'module' => 'drupal_mail_test',
'key' => $index,
])
->mail($message);
}
$captured_emails = $this
->getMails();
$this
->assertCount(6, $captured_emails, 'All emails were captured.');
$captured_emails = $this
->getMails([
'id' => 'drupal_mail_test',
]);
$this
->assertCount(1, $captured_emails, 'Only one email is returned when filtering by id.');
$captured_emails = $this
->getMails([
'id' => 'drupal_mail_test',
'subject' => $subject,
]);
$this
->assertCount(1, $captured_emails, 'Only one email is returned when filtering by id and subject.');
$captured_emails = $this
->getMails([
'id' => 'drupal_mail_test',
'subject' => $subject,
'from' => 'this_was_not_used@example.com',
]);
$this
->assertCount(0, $captured_emails, 'No emails are returned when querying with an unused from address.');
$mail_service
->getInstance([
'module' => 'drupal_mail_test',
'key' => $index,
])
->mail($message);
$captured_emails = $this
->getMails([
'id' => 'drupal_mail_test_4',
]);
$this
->assertCount(2, $captured_emails, 'All emails with the same id are returned when filtering by id.');
}
}