The code examples below assumes PHP 5.4 or newer - if you're on 5.3 you'll need to add $self = $this
before the following code and use ($self)
on the first closure, and replace all references to $this
inside the closure.
Mocking SwiftMailer
The simplest way is to mock the Swift_Mailer instance. You'll have to read up on what methods exist on the Swift_Message class in order to take full advantage of it.
$mock = Mockery::mock('Swift_Mailer');
$this->app['mailer']->setSwiftMailer($mock);
$mock->shouldReceive('send')->once()
->andReturnUsing(function(\Swift_Message $msg) {
$this->assertEquals('My subject', $msg->getSubject());
$this->assertEquals('[email protected]', $msg->getTo());
$this->assertContains('Some string', $msg->getBody());
});
Assertions on closures
Another way to solve this is to run assertions on the closure passed to Mail::send
. This does not look all that clean, and its error messages can be rather cryptic, but it works, is very flexible, and the technique can be used for other things as well.
use Mockery as m;
Mail::shouldReceive('send')->once()
->with('view.name', m::on(function($data) {
$this->assertContains('my variable', $data);
return true;
}), m::on(function($closure) {
$message = m::mock('Illuminate\Mailer\Message');
$message->shouldReceive('to')
->with('[email protected]')
->andReturn(m::self());
$message->shouldReceive('subject')
->with('Email subject')
->andReturn(m::self());
$closure($message);
return true;
}));
In this example, I'm running an assertion on the data passed to the view, and I'll get an error from Mockery if the recipient address, subject or view name is wrong.
Mockery::on()
allows you to run a closure on a parameter of a mocked method. If it returns false, you'll get the "No matching handler found", but we want to run assertions so we just return true. Mockery::self()
allows for chaining of methods.
If at any point you don't care what a certain parameter of a method call is, you can use Mockery::any()
to tell Mockery that it accepts anything.