Mocking

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 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 binding. This will instruct the container to use your mocked instance of the object instead of constructing the object itself:

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

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:

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

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

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

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

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

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

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