gpt4 book ai didi

symfony - 如何在功能测试中测试电子邮件(Symfony2)

转载 作者:行者123 更新时间:2023-12-02 12:07:41 24 4
gpt4 key购买 nike

我正在尝试在功能测试中测试电子邮件...

我的源代码与 example of the cookbook 相同,

Controller :

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

测试:

// src/Acme/DemoBundle/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 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()
);
}
}

但是我收到了这个错误:

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

问题来自这一行:

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

有什么想法吗?

最佳答案

抛出异常是因为如果未启用探查器,getProfile() 返回 false。请参阅here .

public function getProfile()
{
if (!$this->kernel->getContainer()->has('profiler')) {
return false;
}

return $this->kernel->getContainer()->get('profiler')->loadProfileFromResponse($this->response);
}

此外,enableProfiler()仅在向服务容器注册(即启用)时才启用探查器。请参阅here .

public function enableProfiler()
{
if ($this->kernel->getContainer()->has('profiler')) {
$this->profiler = true;
}
}

现在您必须确保在测试环境中启用探查器。 (通常应该是 default setting )

config_test.yml

framework:
profiler:
enabled: true

您可以将这样的内容添加到您的测试中:

$this->assertEquals($this->kernel->getContainer()->has('profiler'), true);

关于symfony - 如何在功能测试中测试电子邮件(Symfony2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17279072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com