03.12.2015 Views

laravel4cookbook

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Controller Testing 367<br />

43<br />

44 return true;<br />

45 });<br />

46 }<br />

47<br />

48 protected function getMailerMock()<br />

49 {<br />

50 return Mockery::mock("Illuminate\Mail\Mailer");<br />

51 }<br />

52 }<br />

.<br />

This file should be saved as app/tests/Formativ/PostMailerTest.php.<br />

Phew! Let’s break that up so it’s easier to digest…<br />

1 Mockery::mock("Illuminate\Mail\Mailer");<br />

Part of trying to test in the most isolated manner is substituting dependencies with things that<br />

don’t perform any significant function. We do this by creating a new mock instance, via the<br />

Mockery::mock() method.<br />

We use this again with:<br />

1 $emailMock = Mockery::mock("stdClass");<br />

We can use stdClass the second time around because the provided class isn’t type-hinted. Our<br />

PostMailer class type-hints the IlluminateMailMailer class.<br />

We then tell the test to expect that certain methods are called using certain arguments:<br />

1 $emailMock<br />

2 ->shouldReceive("to")<br />

3 ->atLeast()<br />

4 ->once()<br />

5 ->with("foo");<br />

This tells the mock to expect a call to an as-yet undefined to() method, and to expect that it will be<br />

passed “foo” as the first (and single) argument. If your production code expects a stubbed method<br />

to return a specific kind of data, you can add the andReturn() method.<br />

We can provide expected callbacks, though it’s slightly trickier:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!