Skip to content

Instantly share code, notes, and snippets.

@johnwards
Created August 1, 2011 11:14
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnwards/1117957 to your computer and use it in GitHub Desktop.
Save johnwards/1117957 to your computer and use it in GitHub Desktop.
Testing Swiftmailer in a Silex app
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Logger;
/**
* MessageLogger.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Clément JOBEILI <clement.jobeili@gmail.com>
*/
class MessageLogger implements \Swift_Events_SendListener
{
/**
* @var array
*/
protected $messages;
public function __construct()
{
$this->messages = array();
}
/**
* Get the message list
*
* @return array
*/
public function getMessages()
{
return $this->messages;
}
/**
* Get the message count
*
* @return int count
*/
public function countMessages()
{
return count($this->messages);
}
/**
* Empty the message list
*
*/
public function clear()
{
$this->messages = array();
}
/**
* Invoked immediately before the Message is sent.
*
* @param \Swift_Events_SendEvent $evt
*/
public function beforeSendPerformed(\Swift_Events_SendEvent $evt)
{
$this->messages[] = clone $evt->getMessage();
}
/**
* Invoked immediately after the Message is sent.
*
* @param \Swift_Events_SendEvent $evt
*/
public function sendPerformed(\Swift_Events_SendEvent $evt)
{
}
}
<?php
use Silex\WebTestCase;
class SwiftTest extends WebTestCase
{
public function createApplication()
{
$app = require __DIR__.'/../src/app.php';
$app["swiftmailer.transport"] = new \Swift_Transport_NullTransport($app['swiftmailer.transport.eventdispatcher']);
$app['mailer.logger'] = new Logger\MessageLogger();
$app['mailer']->registerPlugin($app['mailer.logger']);
return $app;
}
public function sendTest()
{
$client = $this->createClient();
$crawler = $client->request('POST', '/', array("somedata"=>"to_send"));
$this->assertEquals(1, $this->app['mailer.logger']->countMessages(), "Only one email sent");
$emails = $this->app['mailer.logger']->getMessages();
$this->assertEquals("This is my subject", $emails[0]->getSubject(), "Subject is correct");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment