Assetic Bundles 缓存 Composer 配置 控制台 控制器 调试 部署 Doctrine 电子邮件 事件分发器 表达式 表单 前端 日志 分析器 请求 路由 安全 序列化 服务容器 会话 PSR 7 Symfony 版本 模板 测试 升级 验证 Web 服务器 Web 服务 工作流

发布于 2015-12-06 07:33:39 | 171 次阅读 | 评论: 0 | 来源: 网络整理

由于 SwiftmailerBundle 的缘故,用 Symfony 发送电子邮件是相当简单的,是利用 Swift Mailer 库的能力。

要功能测试电子邮件是否发送,甚至判断电子邮件主题,内容或者其他标题,您可以使用 Symfony 分析器

开始先用一个简单的控制器动作发送一封电子邮件:

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(...);
}

不要忘记按照在如何在功能测试中使用编译器解释的那样启动分析器。

在您的功能测试中,在分析器中使用 swiftmailer 收集器来获取关于发送在之前请求上的消息的信息:

// src/AppBundle/Tests/Controller/MailControllerTest.php
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

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 email was sent
        $this->assertEquals(1, $mailCollector->getMessageCount());

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

        // Asserting email 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号  版权声明  广告服务