Skip to content

Instantly share code, notes, and snippets.

@lasekmiroslaw
Last active July 24, 2018 20:00
Show Gist options
  • Save lasekmiroslaw/84b8d60b9e2edcbdd94aa6cf76fdae4b to your computer and use it in GitHub Desktop.
Save lasekmiroslaw/84b8d60b9e2edcbdd94aa6cf76fdae4b to your computer and use it in GitHub Desktop.
Testing Mailer with mock
class Mailer
{
/**
* @var \Swift_Mailer
*/
private $mailer;
/**
* @var \Twig_Environment
*/
private $twig;
/**
* @var string
*/
private $mailFrom;
public function __construct(
\Swift_Mailer $mailer,
\Twig_Environment $twig,
string $mailFrom)
{
$this->mailer = $mailer;
$this->twig = $twig;
$this->mailFrom = $mailFrom;
}
public function sendConfirmationEmail(User $user)
{
$body = $this->twig->render(
'email/registration.html.twig', [
'user' => $user
]);
$message = (new \Swift_Message())
->setSubject('Welcome to the micro-post app')
->setFrom($this->mailFrom)
->setTo($user->getEmail())
->setBody($body, 'text/html');
$this->mailer->send($message);
}
}
class MailerTest extends TestCase
{
public function testConfirmationEmail()
{
$user = new User();
$user->setEmail('miro@miro.com');
$swiftMailer = $this->getMockBuilder(\Swift_Mailer::class)
->disableOriginalConstructor()
->getMock();
$swiftMailer->expects($this->once())->method('send')
->with($this->callback(function ($subject) {
$messageStr = (string)$subject;
return strpos($messageStr, "From: me@domain.com") !== false
&& strpos($messageStr, 'Content-Type: text/html; charset=utf-8') !== false
&& strpos($messageStr, 'Subject: Welcome to the micro-post app') !==false
&& strpos($messageStr, 'To: miro@miro.com') !==false
&& strpos($messageStr, 'This is a message body') !==false;
}));
$twigMock = $this->getMockBuilder(\Twig_Environment::class)
->disableOriginalConstructor()
->getMock();
$twigMock->expects($this->once())->method('render')
->with('email/registration.html.twig',
[
'user' => $user
]
)->willReturn('This is a message body');
$mailer = new Mailer($swiftMailer, $twigMock, 'me@domain.com');
$mailer->sendConfirmationEmail($user);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment