[英]Mock Mailer in Symfony service
I want to unit test this simple service:我想对这个简单的服务进行单元测试:
/**
* Class Messager
* @package AppBundle\Services
*/
class Messager
{
private $mailer = null;
private $templating = null;
/**
* Messager constructor.
* @param \Swift_Mailer $mailer
*/
public function __construct(\Swift_Mailer $mailer, TwigEngine $templating)
{
$this->mailer = $mailer;
$this->templating = $templating;
}
/**
* Send mail
* @param string $email
* @param string $message
* @return bool
*/
public function handleMessage(string $email, string $content) : bool
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL) || strlen($content) < 25) {
return false;
}
$message = \Swift_Message::newInstance()
->setSubject('[DadaPleasure] Incoming message from user')
->setFrom($email)
->setTo('my.e@mail.com')
->setBody($this->templating->render('Emails/contact.html.twig', array('email' => $email, 'message' => $content)), 'text/html');
$this->mailer->send($message);
return true;
}
}
So, I'm doing this currently:所以,我目前正在这样做:
class MessagerTest extends TestConfig
{
public function testSendWrongMessage()
{
$mailer = $this->getMockBuilder('Swift_Mailer')
->disableOriginalConstructor()
->getMock();
self::$container->set('swiftmailer.mailer.default', $mailer);
$this->assertFalse(self::$container->get('app.messager')->handleMessage('hello', 'world'));
$mailer->expects($this->never())->method('send');
}
public function testSendValidEmail()
{
$mailer = $this->getMockBuilder('Swift_Mailer')
->disableOriginalConstructor()
->getMock();
$messager = new Messager($mailer, self::$container->get('templating'));
$this->assertTrue($messager->handleMessage('me@myself.com', 'worldworldworldworldworld'));
$mailer->expects($this->once())->method('send');
}
}
But it seems like send
is never called because I got this return:但似乎从未调用过
send
因为我得到了这个回报:
Expectation failed for method name is equal to when invoked 1 time(s).
方法名称的期望失败等于调用 1 次时。 Method was expected to be called 1 times, actually called 0 times.
方法预期调用 1 次,实际调用 0 次。
If I add var_dump
, my function pass by $this-mailer->send
but I don't know why the assert fails.如果我添加
var_dump
,我的函数通过$this-mailer->send
但我不知道为什么断言失败。
What am I doing wrong?我究竟做错了什么?
Move the expectation declaration before the utilisation, as example:在使用之前移动期望声明,例如:
$mailer->expects($this->once())->method('send');
$messager = new Messager($mailer, self::$container->get('templating'));
$this->assertTrue($messager->handleMessage('me@myself.com', 'worldworldworldworldworld'));
Hope this help希望这有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.