New in Symfony 4.4: PHPUnit Assertions for Email Messages
October 16, 2019 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
The new Mailer and Mime components were introduced in Symfony 4.3 to replace the previous solution based on SwiftMailer. In Symfony 4.4 we've improved them with new PHPUnit assertions to test emails.
The new assertions follow the same philosophy of the test assertions introduced in Symfony 4.3, with long but expressive method names:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// tests/Controller/DefaultControllerTest.php
namespace App\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class DefaultControllerTest extends WebTestCase
{
public function testSomething()
{
$client = static::createClient();
$client->request('GET', '/newsletter-signup');
// ...
$this->assertEmailCount(2);
$this->assertEmailIsQueued($this->getMailerEvent(0));
$email = $this->getMailerMessage(0);
$this->assertEmailHeaderSame($email, 'To', 'fabien@symfony.com');
$this->assertEmailTextBodyContains($email, 'Welcome to Symfony!');
$this->assertEmailAttachementCount($email, 1);
}
}
This is the full list of mailer assertions:
assertEmailCount()
assertQueuedEmailCount()
assertEmailIsQueued()
assertEmailIsNotQueued()
assertEmailAttachementCount()
assertEmailTextBodyContains()
assertEmailTextBodyNotContains()
assertEmailHtmlBodyContains()
assertEmailHtmlBodyNotContains()
assertEmailHasHeader()
assertEmailNotHasHeader()
assertEmailHeaderSame()
assertEmailHeaderNotSame()
assertEmailAddressContains()
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
So great! So useful! Thanks!