Symfony服务中的模拟邮件



我想单元测试此简单服务:

/**
 * Class Messager
 * @package AppBundleServices
 */
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;
    }
}

所以,我目前正在这样做:

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');
    }
}

,但似乎send从未被调用,因为我得到了此返回:

方法名称的期望失败与调用1次调用时相当。 预计方法将被称为1次,实际上称为0次。

如果添加了var_dump,我的功能通过$this-mailer->send,但我不知道为什么断言失败。

我在做什么错?

在利用前移动期望声明,例如:

$mailer->expects($this->once())->method('send');
$messager = new Messager($mailer, self::$container->get('templating'));
$this->assertTrue($messager->handleMessage('me@myself.com', 'worldworldworldworldworld'));

希望此帮助

最新更新