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. Of course, you are free to use Mockery or PHPUnit to create your own mocks or spies.

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.

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. // Perform order shipping...
  14. Mail::assertSent(OrderShipped::class, function ($mail) use ($order) {
  15. return $mail->order->id === $order->id;
  16. });
  17. // Assert a message was sent to the given users...
  18. Mail::assertSent(OrderShipped::class, function ($mail) use ($user) {
  19. return $mail->hasTo($user->email) &&
  20. $mail->hasCc('...') &&
  21. $mail->hasBcc('...');
  22. });
  23. // Assert a mailable was sent twice...
  24. Mail::assertSent(OrderShipped::class, 2);
  25. // Assert a mailable was not sent...
  26. Mail::assertNotSent(AnotherMailable::class);
  27. }
  28. }

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\Foundation\Testing\RefreshDatabase;
  7. use Illuminate\Foundation\Testing\WithoutMiddleware;
  8. class ExampleTest extends TestCase
  9. {
  10. public function testOrderShipping()
  11. {
  12. Notification::fake();
  13. // Perform order shipping...
  14. Notification::assertSentTo(
  15. $user,
  16. OrderShipped::class,
  17. function ($notification, $channels) use ($order) {
  18. return $notification->order->id === $order->id;
  19. }
  20. );
  21. // Assert a notification was sent to the given users...
  22. Notification::assertSentTo(
  23. [$user], OrderShipped::class
  24. );
  25. // Assert a notification was not sent...
  26. Notification::assertNotSentTo(
  27. [$user], AnotherNotification::class
  28. );
  29. }
  30. }

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. // Perform order shipping...
  14. Queue::assertPushed(ShipOrder::class, function ($job) use ($order) {
  15. return $job->order->id === $order->id;
  16. });
  17. // Assert a job was pushed to a given queue...
  18. Queue::assertPushedOn('queue-name', ShipOrder::class);
  19. // Assert a job was pushed twice...
  20. Queue::assertPushed(ShipOrder::class, 2);
  21. // Assert a job was not pushed...
  22. Queue::assertNotPushed(AnotherJob::class);
  23. }
  24. }

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 testAvatarUpload()
  11. {
  12. Storage::fake('avatars');
  13. $response = $this->json('POST', '/avatar', [
  14. 'avatar' => UploadedFile::fake()->image('avatar.jpg')
  15. ]);
  16. // Assert the file was stored...
  17. Storage::disk('avatars')->assertExists('avatar.jpg');
  18. // Assert a file does not exist...
  19. Storage::disk('avatars')->assertMissing('missing.jpg');
  20. }
  21. }

{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.