Symfony PHPUnit mock SwiftMailer


Symfony PHPUnit mock SwiftMailer

我对我的端点(api操作)postLeadAction进行了功能测试,在刷新新实体后,我会发送电子邮件表示祝贺。我发送电子邮件与帮助SwiftMailer与传输sendGrid。以及如何在发送电子邮件之前检查对象,从姓名,从电子邮件,到电子邮件。现在,我使用--env=test运行测试,并在测试环境的配置swiftmailer中添加spool参数以放置目录的电子邮件文件,而不发送电子邮件

如何模拟swiftMailer和发送电子邮件前的检查参数?

这是我的配置测试yml

swiftmailer:
default_mailer: default
mailers:
    default:
        transport: %mailer_transport%
        host: '%mailer_host%'
        port: 587
        encryption: ~
        username: '%mailer_user%'
        password: '%mailer_password%'
        spool:
            type: file
            path: '%kernel.root_dir%/spool'

此MailerWrapper类,使用SwiftMailer函数"发送"发送电子邮件

class MailerWrapper
{
protected $mailer;
/**
 * @var 'Swift_Message
 */
  //some parameters
public function __construct('Swift_Mailer $mailer)
{
    $this->mailer = $mailer;
}
public function newMessage()
{
    //some parameters
    return $this;
}
public function send()
{
   //some logic with message
    return $this->mailer->send($this->message);
}

我喜欢食谱

// Enable the profiler for the next request (it does nothing if the profiler is not available)
$this->client->enableProfiler();
$mailCollector = $this->client->getProfile()->getCollector('swiftmailer.mailer.default');
// Check that an email was sent
$this->assertEquals(1, $mailCollector->getMessageCount());
$collectedMessages = $mailCollector->getMessages();
$message = $collectedMessages[0];

但有错误

PHP Fatal error:  Call to a member function getCollector() on a non-object

更新

在配置中,我不启用配置文件

framework:
    test: ~
    session:
        storage_id: session.storage.mock_file
        cookie_httponly: true
        cookie_secure: true
    profiler:
        collect: false

但我有错误,因为我在http请求后启用配置文件,当我在之前启用时-一切都好

$client->enableProfiler();
$this->request(
    'post',
    $this->generateUrl('post_lead', [], UrlGeneratorInterface::RELATIVE_PATH),
    [],
    [
     // some parameters
    ]
);
$mailCollector = $client->getProfile()->getCollector('swiftmailer');

我用Symfony 2.8进行了测试,我必须在配置中启用探查器:

# app/config_test.yml
framework:
    profiler:
        enabled: true
        collect: false

您的测试应该在定义了enabled: true之后才能工作。

为了避免在我的测试中出现PHP致命错误,我在测试电子邮件之前添加了一个小检查:

// Enable the profiler for the next request (it does nothing if the profiler is not available)
$this->client->enableProfiler();
// Check that the profiler is available.
if ($profile = $this->client->getProfile()) {
    $mailCollector = $profile->getCollector('swiftmailer');
    // Check that an e-mail was sent
    $this->assertEquals(1, $mailCollector->getMessageCount());
    // …
}
else {
    $this->markTestIncomplete(
        'Profiler is disabled.'
    );
}

通过此检查,PHPUnit将测试标记为不完整,而不是返回错误并破坏测试套件。