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 dispatches 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. You can also use Mockery or PHPUnit to create your own mocks or spies.

Mocking Objects

When mocking an object that is going to be injected into your application via Laravel's service container, you will need to bind your mocked instance into the container as an instance binding. This will instruct the container to use your mocked instance of the object instead of constructing the object itself:

  1. use Mockery;
  2. use App\Service;
  3. $this->instance(Service::class, Mockery::mock(Service::class, function ($mock) {
  4. $mock->shouldReceive('process')->once();
  5. }));

In order to make this more convenient, you may use the mock method, which is provided by Laravel's base test case class:

  1. use App\Service;
  2. $this->mock(Service::class, function ($mock) {
  3. $mock->shouldReceive('process')->once();
  4. });

Similarly, if you want to spy on an object, Laravel's base test case class offers a spy method as a convenient wrapper around the Mockery::spy method:

  1. use App\Service;
  2. $this->spy(Service::class, function ($mock) {
  3. $mock->shouldHaveReceived('process');
  4. });

Bus Fake

As an alternative to mocking, you may use the Bus facade's fake method to prevent jobs from being dispatched. When using fakes, assertions are made after the code under test is executed:

  1. <?php
  2. namespace Tests\Feature;
  3. use Tests\TestCase;
  4. use App\Jobs\ShipOrder;
  5. use Illuminate\Support\Facades\Bus;
  6. use Illuminate\Foundation\Testing\RefreshDatabase;
  7. use Illuminate\Foundation\Testing\WithoutMiddleware;
  8. class ExampleTest extends TestCase
  9. {
  10. public function testOrderShipping()
  11. {
  12. Bus::fake();
  13. // Perform order shipping...
  14. Bus::assertDispatched(ShipOrder::class, function ($job) use ($order) {
  15. return $job->order->id === $order->id;
  16. });
  17. // Assert a job was not dispatched...
  18. Bus::assertNotDispatched(AnotherJob::class);
  19. }
  20. }

Event Fake

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 dispatched and even inspect the data they received. When using fakes, assertions are made after the code under test is executed:

  1. <?php
  2. namespace Tests\Feature;
  3. use Tests\TestCase;
  4. use App\Events\OrderShipped;
  5. use App\Events\OrderFailedToShip;
  6. use Illuminate\Support\Facades\Event;
  7. use Illuminate\Foundation\Testing\RefreshDatabase;
  8. use Illuminate\Foundation\Testing\WithoutMiddleware;
  9. class ExampleTest extends TestCase
  10. {
  11. /**
  12. * Test order shipping.
  13. */
  14. public function testOrderShipping()
  15. {
  16. Event::fake();
  17. // Perform order shipping...
  18. Event::assertDispatched(OrderShipped::class, function ($e) use ($order) {
  19. return $e->order->id === $order->id;
  20. });
  21. // Assert an event was dispatched twice...
  22. Event::assertDispatched(OrderShipped::class, 2);
  23. // Assert an event was not dispatched...
  24. Event::assertNotDispatched(OrderFailedToShip::class);
  25. }
  26. }

{note} After calling Event::fake(), no event listeners will be executed. So, if your tests use model factories that rely on events, such as creating a UUID during a model's creating event, you should call Event::fake() after using your factories.

Faking A Subset Of Events

If you only want to fake event listeners for a specific set of events, you may pass them to the fake or fakeFor method:

  1. /**
  2. * Test order process.
  3. */
  4. public function testOrderProcess()
  5. {
  6. Event::fake([
  7. OrderCreated::class,
  8. ]);
  9. $order = factory(Order::class)->create();
  10. Event::assertDispatched(OrderCreated::class);
  11. // Other events are dispatched as normal...
  12. $order->update([...]);
  13. }

Scoped Event Fakes

If you only want to fake event listeners for a portion of your test, you may use the fakeFor method:

  1. <?php
  2. namespace Tests\Feature;
  3. use App\Order;
  4. use Tests\TestCase;
  5. use App\Events\OrderCreated;
  6. use Illuminate\Support\Facades\Event;
  7. use Illuminate\Foundation\Testing\RefreshDatabase;
  8. use Illuminate\Foundation\Testing\WithoutMiddleware;
  9. class ExampleTest extends TestCase
  10. {
  11. /**
  12. * Test order process.
  13. */
  14. public function testOrderProcess()
  15. {
  16. $order = Event::fakeFor(function () {
  17. $order = factory(Order::class)->create();
  18. Event::assertDispatched(OrderCreated::class);
  19. return $order;
  20. });
  21. // Events are dispatched as normal and observers will run ...
  22. $order->update([...]);
  23. }
  24. }

Mail Fake

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. namespace Tests\Feature;
  3. use Tests\TestCase;
  4. use App\Mail\OrderShipped;
  5. use Illuminate\Support\Facades\Mail;
  6. use Illuminate\Foundation\Testing\RefreshDatabase;
  7. use Illuminate\Foundation\Testing\WithoutMiddleware;
  8. class ExampleTest extends TestCase
  9. {
  10. public function testOrderShipping()
  11. {
  12. Mail::fake();
  13. // Assert that no mailables were sent...
  14. Mail::assertNothingSent();
  15. // Perform order shipping...
  16. Mail::assertSent(OrderShipped::class, function ($mail) use ($order) {
  17. return $mail->order->id === $order->id;
  18. });
  19. // Assert a message was sent to the given users...
  20. Mail::assertSent(OrderShipped::class, function ($mail) use ($user) {
  21. return $mail->hasTo($user->email) &&
  22. $mail->hasCc('...') &&
  23. $mail->hasBcc('...');
  24. });
  25. // Assert a mailable was sent twice...
  26. Mail::assertSent(OrderShipped::class, 2);
  27. // Assert a mailable was not sent...
  28. Mail::assertNotSent(AnotherMailable::class);
  29. }
  30. }

If you are queueing mailables for delivery in the background, you should use the assertQueued method instead of assertSent:

  1. Mail::assertQueued(...);
  2. Mail::assertNotQueued(...);

Notification Fake

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. namespace Tests\Feature;
  3. use Tests\TestCase;
  4. use App\Notifications\OrderShipped;
  5. use Illuminate\Support\Facades\Notification;
  6. use Illuminate\Notifications\AnonymousNotifiable;
  7. use Illuminate\Foundation\Testing\RefreshDatabase;
  8. use Illuminate\Foundation\Testing\WithoutMiddleware;
  9. class ExampleTest extends TestCase
  10. {
  11. public function testOrderShipping()
  12. {
  13. Notification::fake();
  14. // Assert that no notifications were sent...
  15. Notification::assertNothingSent();
  16. // Perform order shipping...
  17. Notification::assertSentTo(
  18. $user,
  19. OrderShipped::class,
  20. function ($notification, $channels) use ($order) {
  21. return $notification->order->id === $order->id;
  22. }
  23. );
  24. // Assert a notification was sent to the given users...
  25. Notification::assertSentTo(
  26. [$user], OrderShipped::class
  27. );
  28. // Assert a notification was not sent...
  29. Notification::assertNotSentTo(
  30. [$user], AnotherNotification::class
  31. );
  32. // Assert a notification was sent via Notification::route() method...
  33. Notification::assertSentTo(
  34. new AnonymousNotifiable, OrderShipped::class
  35. );
  36. }
  37. }

Queue Fake

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. namespace Tests\Feature;
  3. use Tests\TestCase;
  4. use App\Jobs\ShipOrder;
  5. use Illuminate\Support\Facades\Queue;
  6. use Illuminate\Foundation\Testing\RefreshDatabase;
  7. use Illuminate\Foundation\Testing\WithoutMiddleware;
  8. class ExampleTest extends TestCase
  9. {
  10. public function testOrderShipping()
  11. {
  12. Queue::fake();
  13. // Assert that no jobs were pushed...
  14. Queue::assertNothingPushed();
  15. // Perform order shipping...
  16. Queue::assertPushed(ShipOrder::class, function ($job) use ($order) {
  17. return $job->order->id === $order->id;
  18. });
  19. // Assert a job was pushed to a given queue...
  20. Queue::assertPushedOn('queue-name', ShipOrder::class);
  21. // Assert a job was pushed twice...
  22. Queue::assertPushed(ShipOrder::class, 2);
  23. // Assert a job was not pushed...
  24. Queue::assertNotPushed(AnotherJob::class);
  25. // Assert a job was pushed with a specific chain...
  26. Queue::assertPushedWithChain(ShipOrder::class, [
  27. AnotherJob::class,
  28. FinalJob::class
  29. ]);
  30. }
  31. }

Storage Fake

The Storage facade's fake method allows you to easily generate a fake disk that, combined with the file generation utilities of the UploadedFile class, greatly simplifies the testing of file uploads. For example:

  1. <?php
  2. namespace Tests\Feature;
  3. use Tests\TestCase;
  4. use Illuminate\Http\UploadedFile;
  5. use Illuminate\Support\Facades\Storage;
  6. use Illuminate\Foundation\Testing\RefreshDatabase;
  7. use Illuminate\Foundation\Testing\WithoutMiddleware;
  8. class ExampleTest extends TestCase
  9. {
  10. public function testAlbumUpload()
  11. {
  12. Storage::fake('photos');
  13. $response = $this->json('POST', '/photos', [
  14. UploadedFile::fake()->image('photo1.jpg'),
  15. UploadedFile::fake()->image('photo2.jpg')
  16. ]);
  17. // Assert one or more files were stored...
  18. Storage::disk('photos')->assertExists('photo1.jpg');
  19. Storage::disk('photos')->assertExists(['photo1.jpg', 'photo2.jpg']);
  20. // Assert one or more files were not stored...
  21. Storage::disk('photos')->assertMissing('missing.jpg');
  22. Storage::disk('photos')->assertMissing(['missing.jpg', 'non-existing.jpg']);
  23. }
  24. }

{tip} By default, the fake method will delete all files in its temporary directory. If you would like to keep these files, you may use the "persistentFake" method instead.

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. namespace Tests\Feature;
  3. use Tests\TestCase;
  4. use Illuminate\Support\Facades\Cache;
  5. use Illuminate\Foundation\Testing\RefreshDatabase;
  6. use Illuminate\Foundation\Testing\WithoutMiddleware;
  7. class UserControllerTest extends TestCase
  8. {
  9. public function testGetIndex()
  10. {
  11. Cache::shouldReceive('get')
  12. ->once()
  13. ->with('key')
  14. ->andReturn('value');
  15. $response = $this->get('/users');
  16. // ...
  17. }
  18. }

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