概述 快速入门 教程 手册 最佳实践 组件 参考 贡献

发布于 2015-08-27 16:43:00 | 83 次阅读 | 评论: 0 | 来源: 网络整理

Sending e-mails with Symfony is pretty straightforward thanks to the SwiftmailerBundle, which leverages the power of the Swift Mailer library.

To functionally test that an email was sent, and even assert the email subject, content or any other headers, you can use the Symfony Profiler.

Start with an easy controller action that sends an e-mail:

public function sendEmailAction($name)
{
    $message = Swift_Message::newInstance()
        ->setSubject('Hello Email')
        ->setFrom('send@example.com')
        ->setTo('recipient@example.com')
        ->setBody('You should see me from the profiler!')
    ;

    $this->get('mailer')->send($message);

    return $this->render(...);
}

注解

Don’t forget to enable the profiler as explained in How to Use the Profiler in a Functional Test.

In your functional test, use the swiftmailer collector on the profiler to get information about the messages send on the previous request:

// src/AppBundle/Tests/Controller/MailControllerTest.php
use SymfonyBundleFrameworkBundleTestWebTestCase;

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

        // Enable the profiler for the next request (it does nothing if the profiler is not available)
        $client->enableProfiler();

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

        $mailCollector = $client->getProfile()->getCollector('swiftmailer');

        // Check that an e-mail was sent
        $this->assertEquals(1, $mailCollector->getMessageCount());

        $collectedMessages = $mailCollector->getMessages();
        $message = $collectedMessages[0];

        // Asserting e-mail data
        $this->assertInstanceOf('Swift_Message', $message);
        $this->assertEquals('Hello Email', $message->getSubject());
        $this->assertEquals('send@example.com', key($message->getFrom()));
        $this->assertEquals('recipient@example.com', key($message->getTo()));
        $this->assertEquals(
            'You should see me from the profiler!',
            $message->getBody()
        );
    }
}
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务