Mocking

Introduction

When testing Laravel applications, you may wish to "mock" certain aspects of your application so they are not actually executed during a given test. For example, when testing a controller that fires an event, you may wish to mock the event listeners so they are not actually executed during the test. This allows you to only test the controller's HTTP response without worrying about the execution of the event listeners, since the event listeners can be tested in their own test case.

Laravel provides helpers for mocking events, jobs, and facades out of the box. These helpers primarily provide a convenience layer over Mockery so you do not have to manually make complicated Mockery method calls. Of course, you are free to use Mockery or PHPUnit to create your own mocks or spies.

Events

Using Mocks

If you are making heavy use of Laravel's event system, you may wish to silence or mock certain events while testing. For example, if you are testing user registration, you probably do not want all of a UserRegistered event's handlers firing, since the listeners may send "welcome" e-mails, etc.

Laravel provides a convenient expectsEvents method which verifies the expected events are fired, but prevents any listeners for those events from executing:

  1. <?php
  2. use App\Events\UserRegistered;
  3. class ExampleTest extends TestCase
  4. {
  5. /**
  6. * Test new user registration.
  7. */
  8. public function testUserRegistration()
  9. {
  10. $this->expectsEvents(UserRegistered::class);
  11. // Test user registration...
  12. }
  13. }

You may use the doesntExpectEvents method to verify that the given events are not fired:

  1. <?php
  2. use App\Events\OrderShipped;
  3. use App\Events\OrderFailedToShip;
  4. class ExampleTest extends TestCase
  5. {
  6. /**
  7. * Test order shipping.
  8. */
  9. public function testOrderShipping()
  10. {
  11. $this->expectsEvents(OrderShipped::class);
  12. $this->doesntExpectEvents(OrderFailedToShip::class);
  13. // Test order shipping...
  14. }
  15. }

If you would like to prevent all event listeners from running, you may use the withoutEvents method. When this method is called, all listeners for all events will be mocked:

  1. <?php
  2. class ExampleTest extends TestCase
  3. {
  4. public function testUserRegistration()
  5. {
  6. $this->withoutEvents();
  7. // Test user registration code...
  8. }
  9. }

Using Fakes

As an alternative to mocking, you may use the Event facade's fake method to prevent all event listeners from executing. You may then assert that events were fired and even inspect the data they received. When using fakes, assertions are made after the code under test is executed:

  1. <?php
  2. use App\Events\OrderShipped;
  3. use App\Events\OrderFailedToShip;
  4. use Illuminate\Support\Facades\Event;
  5. class ExampleTest extends TestCase
  6. {
  7. /**
  8. * Test order shipping.
  9. */
  10. public function testOrderShipping()
  11. {
  12. Event::fake();
  13. // Perform order shipping...
  14. Event::assertFired(OrderShipped::class, function ($e) use ($order) {
  15. return $e->order->id === $order->id;
  16. });
  17. Event::assertNotFired(OrderFailedToShip::class);
  18. }
  19. }

Jobs

Using Mocks

Sometimes, you may wish to test that given jobs are dispatched when making requests to your application. This will allow you to test your routes and controllers in isolation without worrying about your job's logic. Of course, you should then test the job in a separate test case.

Laravel provides the convenient expectsJobs method which will verify that the expected jobs are dispatched. However, the job itself will not be executed:

  1. <?php
  2. use App\Jobs\ShipOrder;
  3. class ExampleTest extends TestCase
  4. {
  5. public function testOrderShipping()
  6. {
  7. $this->expectsJobs(ShipOrder::class);
  8. // Test order shipping...
  9. }
  10. }

{note} This method only detects jobs that are dispatched via the DispatchesJobs trait's dispatch methods or the dispatch helper function. It does not detect queued jobs that are sent directly to Queue::push.

Like the event mocking helpers, you may also test that a job is not dispatched using the doesntExpectJobs method:

  1. <?php
  2. use App\Jobs\ShipOrder;
  3. class ExampleTest extends TestCase
  4. {
  5. /**
  6. * Test order cancellation.
  7. */
  8. public function testOrderCancellation()
  9. {
  10. $this->doesntExpectJobs(ShipOrder::class);
  11. // Test order cancellation...
  12. }
  13. }

Alternatively, you may ignore all dispatched jobs using the withoutJobs method. When this method is called within a test method, all jobs that are dispatched during that test will be discarded:

  1. <?php
  2. use App\Jobs\ShipOrder;
  3. class ExampleTest extends TestCase
  4. {
  5. /**
  6. * Test order cancellation.
  7. */
  8. public function testOrderCancellation()
  9. {
  10. $this->withoutJobs();
  11. // Test order cancellation...
  12. }
  13. }

Using Fakes

As an alternative to mocking, you may use the Queue facade's fake method to prevent jobs from being queued. You may then assert that jobs were pushed to the queue and even inspect the data they received. When using fakes, assertions are made after the code under test is executed:

  1. <?php
  2. use App\Jobs\ShipOrder;
  3. use Illuminate\Support\Facades\Queue;
  4. class ExampleTest extends TestCase
  5. {
  6. public function testOrderShipping()
  7. {
  8. Queue::fake();
  9. // Perform order shipping...
  10. Queue::assertPushed(ShipOrder::class, function ($job) use ($order) {
  11. return $job->order->id === $order->id;
  12. });
  13. // Assert a job was pushed to a given queue...
  14. Queue::assertPushedOn('queue-name', ShipOrder::class);
  15. // Assert a job was not pushed...
  16. Queue::assertNotPushed(AnotherJob::class);
  17. }
  18. }

Mail Fakes

You may use the Mail facade's fake method to prevent mail from being sent. You may then assert that mailables were sent to users and even inspect the data they received. When using fakes, assertions are made after the code under test is executed:

  1. <?php
  2. use App\Mail\OrderShipped;
  3. use Illuminate\Support\Facades\Mail;
  4. class ExampleTest extends TestCase
  5. {
  6. public function testOrderShipping()
  7. {
  8. Mail::fake();
  9. // Perform order shipping...
  10. Mail::assertSent(OrderShipped::class, function ($mail) use ($order) {
  11. return $mail->order->id === $order->id;
  12. });
  13. // Assert a message was sent to the given users...
  14. Mail::assertSentTo([$user], OrderShipped::class);
  15. // Assert a mailable was not sent...
  16. Mail::assertNotSent(AnotherMailable::class);
  17. }
  18. }

Notification Fakes

You may use the Notification facade's fake method to prevent notifications from being sent. You may then assert that notifications were sent to users and even inspect the data they received. When using fakes, assertions are made after the code under test is executed:

  1. <?php
  2. use App\Notifications\OrderShipped;
  3. use Illuminate\Support\Facades\Notification;
  4. class ExampleTest extends TestCase
  5. {
  6. public function testOrderShipping()
  7. {
  8. Notification::fake();
  9. // Perform order shipping...
  10. Notification::assertSentTo(
  11. $user,
  12. OrderShipped::class,
  13. function ($notification, $channels) use ($order) {
  14. return $notification->order->id === $order->id;
  15. }
  16. );
  17. // Assert a notification was sent to the given users...
  18. Notification::assertSentTo(
  19. [$user], OrderShipped::class
  20. );
  21. // Assert a notification was not sent...
  22. Notification::assertNotSentTo(
  23. [$user], AnotherNotification::class
  24. );
  25. }
  26. }

Facades

Unlike traditional static method calls, facades may be mocked. This provides a great advantage over traditional static methods and grants you the same testability you would have if you were using dependency injection. When testing, you may often want to mock a call to a Laravel facade in one of your controllers. For example, consider the following controller action:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Support\Facades\Cache;
  4. class UserController extends Controller
  5. {
  6. /**
  7. * Show a list of all users of the application.
  8. *
  9. * @return Response
  10. */
  11. public function index()
  12. {
  13. $value = Cache::get('key');
  14. //
  15. }
  16. }

We can mock the call to the Cache facade by using the shouldReceive method, which will return an instance of a Mockery mock. Since facades are actually resolved and managed by the Laravel service container, they have much more testability than a typical static class. For example, let's mock our call to the Cache facade's get method:

  1. <?php
  2. class FooTest extends TestCase
  3. {
  4. public function testGetIndex()
  5. {
  6. Cache::shouldReceive('get')
  7. ->once()
  8. ->with('key')
  9. ->andReturn('value');
  10. $this->visit('/users')->see('value');
  11. }
  12. }

{note} You should not mock the Request facade. Instead, pass the input you desire into the HTTP helper methods such as call and post when running your test. Likewise, instead of mocking the Config facade, simply call the Config::set method in your tests.