我正在尝试在功能测试中测试电子邮件......
我的源代码是一样的食谱的例子 http://symfony.com/doc/current/cookbook/email/testing.html,
控制器:
public function sendEmailAction($name)
{
$message = \Swift_Message::newInstance()
->setSubject('Hello Email')
->setFrom('[email protected] /cdn-cgi/l/email-protection')
->setTo('[email protected] /cdn-cgi/l/email-protection')
->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('[email protected] /cdn-cgi/l/email-protection', key($message->getFrom()));
$this->assertEquals('[email protected] /cdn-cgi/l/email-protection', key($message->getTo()));
$this->assertEquals(
'You should see me from the profiler!',
$message->getBody()
);
}
}
但是我收到了这个错误:
PHP 致命错误:调用成员函数 getCollector()
非对象
问题来自这一行:
$mailCollector = $client->getProfile()->getCollector('swiftmailer');
任何想法 ?
抛出异常是因为getProfile()
如果未启用探查器,则返回 false。看here https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/FrameworkBundle/Client.php#L66.
public function getProfile()
{
if (!$this->kernel->getContainer()->has('profiler')) {
return false;
}
return $this->kernel->getContainer()->get('profiler')->loadProfileFromResponse($this->response);
}
此外enableProfiler()
仅当分析器注册到服务容器(即启用)时才启用分析器。看here https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/FrameworkBundle/Client.php#L80.
public function enableProfiler()
{
if ($this->kernel->getContainer()->has('profiler')) {
$this->profiler = true;
}
}
现在您必须确保在测试环境中启用探查器。 (通常应该是默认设置 http://symfony.com/doc/current/reference/configuration/framework.html#profiler )
配置测试.yml
framework:
profiler:
enabled: true
您可以将这样的内容添加到您的测试中:
$this->assertEquals($this->kernel->getContainer()->has('profiler'), true);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)