Skip to content

[Mailer] Add a section about testing #15926

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions mailer.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1121,6 +1121,57 @@ a specific address, instead of the *real* address:
],
]);

How to Test that an Email is Sent in a Functional Test
------------------------------------------------------

To functionally test that an email was sent, and even assert the email subject,
content or any other headers, you can use the methods in
:class:`Symfony\\Bundle\\FrameworkBundle\\Test\\MailerAssertionsTrait`

Start with a controller action that sends an email::

public function sendEmail(MailerInterface $mailer)
{
$message = new Email();
$message
->from('send@example.com')
->to('recipient@example.com')
->text('This is my message')
;

$mailer->send($message);

// ...
}

In your functional test, assert the data of the message sent on the previous request::

// tests/Controller/MailControllerTest.php
namespace App\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class MailControllerTest extends WebTestCase
{
public function testMailIsSentAndContentIsOk()
{
$client = static::createClient();

$crawler = $client->request('POST', '/path/to/above/action');

// checks that an email was sent
$this->assertEmailCount(1);

$messages = $this->getMailerMessages();
$message = $messages[0];

// Asserting email data
$this->assertEmailAddressContains($message, 'From', 'send@example.com');
$this->assertEmailAddressContains($message, 'To', 'recipient@example.com');
$this->assertEmailTextBodyContains($message, 'This is my message');
}
}

.. _`high availability`: https://en.wikipedia.org/wiki/High_availability
.. _`load balancing`: https://en.wikipedia.org/wiki/Load_balancing_(computing)
.. _`download the foundation-emails.css file`: https://github.com/foundation/foundation-emails/blob/develop/dist/foundation-emails.css
Expand Down