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 helpful methods for mocking events, jobs, and other 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.

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 App\Service;
  2. use Mockery;
  3. use Mockery\MockInterface;
  4. public function test_something_can_be_mocked()
  5. {
  6. $this->instance(
  7. Service::class,
  8. Mockery::mock(Service::class, function (MockInterface $mock) {
  9. $mock->shouldReceive('process')->once();
  10. })
  11. );
  12. }

In order to make this more convenient, you may use the mock method that is provided by Laravel’s base test case class. For example, the following example is equivalent to the example above:

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

You may use the partialMock method when you only need to mock a few methods of an object. The methods that are not mocked will be executed normally when called:

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

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. Spies are similar to mocks; however, spies record any interaction between the spy and the code being tested, allowing you to make assertions after the code is executed:

  1. use App\Service;
  2. $spy = $this->spy(Service::class);
  3. // ...
  4. $spy->shouldHaveReceived('process');

Mocking Facades

Unlike traditional static method calls, facades (including real-time facades) may be mocked. This provides a great advantage over traditional static methods and grants you the same testability that you would have if you were using traditional dependency injection. When testing, you may often want to mock a call to a Laravel facade that occurs 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. * Retrieve a list of all users of the application.
  8. *
  9. * @return \Illuminate\Http\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 Illuminate\Foundation\Testing\RefreshDatabase;
  4. use Illuminate\Foundation\Testing\WithoutMiddleware;
  5. use Illuminate\Support\Facades\Cache;
  6. use Tests\TestCase;
  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 testing 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.

Facade Spies

If you would like to spy on a facade, you may call the spy method on the corresponding facade. Spies are similar to mocks; however, spies record any interaction between the spy and the code being tested, allowing you to make assertions after the code is executed:

  1. use Illuminate\Support\Facades\Cache;
  2. public function test_values_are_be_stored_in_cache()
  3. {
  4. Cache::spy();
  5. $response = $this->get('/');
  6. $response->assertStatus(200);
  7. Cache::shouldHaveReceived('put')->once()->with('name', 'Taylor', 10);
  8. }

Bus Fake

When testing code that dispatches jobs, you typically want to assert that a given job was dispatched but not actually queue or execute the job. This is because the job’s execution can normally be tested in a separate test class.

You may use the Bus facade’s fake method to prevent jobs from being dispatched to the queue. Then, after executing the code under test, you may inspect which jobs the application attempted to dispatch using the assertDispatched and assertNotDispatched methods:

  1. <?php
  2. namespace Tests\Feature;
  3. use App\Jobs\ShipOrder;
  4. use Illuminate\Foundation\Testing\RefreshDatabase;
  5. use Illuminate\Foundation\Testing\WithoutMiddleware;
  6. use Illuminate\Support\Facades\Bus;
  7. use Tests\TestCase;
  8. class ExampleTest extends TestCase
  9. {
  10. public function test_orders_can_be_shipped()
  11. {
  12. Bus::fake();
  13. // Perform order shipping...
  14. // Assert that a job was dispatched...
  15. Bus::assertDispatched(ShipOrder::class);
  16. // Assert a job was not dispatched...
  17. Bus::assertNotDispatched(AnotherJob::class);
  18. // Assert that a job was dispatched synchronously...
  19. Bus::assertDispatchedSync(AnotherJob::class);
  20. // Assert that a job was not dipatched synchronously...
  21. Bus::assertNotDispatchedSync(AnotherJob::class);
  22. // Assert that a job was dispatched after the response was sent...
  23. Bus::assertDispatchedAfterResponse(AnotherJob::class);
  24. // Assert a job was not dispatched after response was sent...
  25. Bus::assertNotDispatchedAfterResponse(AnotherJob::class);
  26. // Assert no jobs were dispatched...
  27. Bus::assertNothingDispatched();
  28. }
  29. }

You may pass a closure to the available methods in order to assert that a job was dispatched that passes a given “truth test”. If at least one job was dispatched that passes the given truth test then the assertion will be successful. For example, you may wish to assert that a job was dispatched for a specific order:

  1. Bus::assertDispatched(function (ShipOrder $job) use ($order) {
  2. return $job->order->id === $order->id;
  3. });

Job Chains

The Bus facade’s assertChained method may be used to assert that a chain of jobs was dispatched. The assertChained method accepts an array of chained jobs as its first argument:

  1. use App\Jobs\RecordShipment;
  2. use App\Jobs\ShipOrder;
  3. use App\Jobs\UpdateInventory;
  4. use Illuminate\Support\Facades\Bus;
  5. Bus::assertChained([
  6. ShipOrder::class,
  7. RecordShipment::class,
  8. UpdateInventory::class
  9. ]);

As you can see in the example above, the array of chained jobs may be an array of the job’s class names. However, you may also provide an array of actual job instances. When doing so, Laravel will ensure that the job instances are of the same class and have the same property values of the chained jobs dispatched by your application:

  1. Bus::assertChained([
  2. new ShipOrder,
  3. new RecordShipment,
  4. new UpdateInventory,
  5. ]);

Job Batches

The Bus facade’s assertBatched method may be used to assert that a batch of jobs was dispatched. The closure given to the assertBatched method receives an instance of Illuminate\Bus\PendingBatch, which may be used to inspect the jobs within the batch:

  1. use Illuminate\Bus\PendingBatch;
  2. use Illuminate\Support\Facades\Bus;
  3. Bus::assertBatched(function (PendingBatch $batch) {
  4. return $batch->name == 'import-csv' &&
  5. $batch->jobs->count() === 10;
  6. });

Event Fake

When testing code that dispatches events, you may wish to instruct Laravel to not actually execute the event’s listeners. Using the Event facade’s fake method, you may prevent listeners from executing, execute the code under test, and then assert which events were dispatched by your application using the assertDispatched, assertNotDispatched, and assertNothingDispatched methods:

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

You may pass a closure to the assertDispatched or assertNotDispatched methods in order to assert that an event was dispatched that passes a given “truth test”. If at least one event was dispatched that passes the given truth test then the assertion will be successful:

  1. Event::assertDispatched(function (OrderShipped $event) use ($order) {
  2. return $event->order->id === $order->id;
  3. });

If you would simply like to assert that an event listener is listening to a given event, you may use the assertListening method:

  1. Event::assertListening(
  2. OrderShipped::class,
  3. SendShipmentNotification::class
  4. );

{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 test_orders_can_be_processed()
  5. {
  6. Event::fake([
  7. OrderCreated::class,
  8. ]);
  9. $order = Order::factory()->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\Events\OrderCreated;
  4. use App\Models\Order;
  5. use Illuminate\Foundation\Testing\RefreshDatabase;
  6. use Illuminate\Support\Facades\Event;
  7. use Illuminate\Foundation\Testing\WithoutMiddleware;
  8. use Tests\TestCase;
  9. class ExampleTest extends TestCase
  10. {
  11. /**
  12. * Test order process.
  13. */
  14. public function test_orders_can_be_processed()
  15. {
  16. $order = Event::fakeFor(function () {
  17. $order = Order::factory()->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. }

HTTP Fake

The Http facade’s fake method allows you to instruct the HTTP client to return stubbed / dummy responses when requests are made. For more information on faking outgoing HTTP requests, please consult the HTTP Client testing documentation.

Mail Fake

You may use the Mail facade’s fake method to prevent mail from being sent. Typically, sending mail is unrelated to the code you are actually testing. Most likely, it is sufficient to simply assert that Laravel was instructed to send a given mailable.

After calling the Mail facade’s fake method, you may then assert that mailables were instructed to be sent to users and even inspect the data the mailables received:

  1. <?php
  2. namespace Tests\Feature;
  3. use App\Mail\OrderShipped;
  4. use Illuminate\Foundation\Testing\RefreshDatabase;
  5. use Illuminate\Foundation\Testing\WithoutMiddleware;
  6. use Illuminate\Support\Facades\Mail;
  7. use Tests\TestCase;
  8. class ExampleTest extends TestCase
  9. {
  10. public function test_orders_can_be_shipped()
  11. {
  12. Mail::fake();
  13. // Perform order shipping...
  14. // Assert that no mailables were sent...
  15. Mail::assertNothingSent();
  16. // Assert that a mailable was sent...
  17. Mail::assertSent(OrderShipped::class);
  18. // Assert a mailable was sent twice...
  19. Mail::assertSent(OrderShipped::class, 2);
  20. // Assert a mailable was not sent...
  21. Mail::assertNotSent(AnotherMailable::class);
  22. }
  23. }

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

  1. Mail::assertQueued(OrderShipped::class);
  2. Mail::assertNotQueued(OrderShipped::class);
  3. Mail::assertNothingQueued();

You may pass a closure to the assertSent, assertNotSent, assertQueued, or assertNotQueued methods in order to assert that a mailable was sent that passes a given “truth test”. If at least one mailable was sent that passes the given truth test then the assertion will be successful:

  1. Mail::assertSent(function (OrderShipped $mail) use ($order) {
  2. return $mail->order->id === $order->id;
  3. });

When calling the Mail facade’s assertion methods, the mailable instance accepted by the provided closure exposes helpful methods for examining the recipients of the mailable:

  1. Mail::assertSent(OrderShipped::class, function ($mail) use ($user) {
  2. return $mail->hasTo($user->email) &&
  3. $mail->hasCc('...') &&
  4. $mail->hasBcc('...');
  5. });

You may have noticed that there are two methods for asserting that mail was not sent: assertNotSent and assertNotQueued. Sometimes you may wish to assert that no mail was sent or queued. To accomplish this, you may use the assertNothingOutgoing and assertNotOutgoing methods:

  1. Mail::assertNothingOutgoing();
  2. Mail::assertNotOutgoing(function (OrderShipped $mail) use ($order) {
  3. return $mail->order->id === $order->id;
  4. });

Notification Fake

You may use the Notification facade’s fake method to prevent notifications from being sent. Typically, sending notifications is unrelated to the code you are actually testing. Most likely, it is sufficient to simply assert that Laravel was instructed to send a given notification.

After calling the Notification facade’s fake method, you may then assert that notifications were instructed to be sent to users and even inspect the data the notifications received:

  1. <?php
  2. namespace Tests\Feature;
  3. use App\Notifications\OrderShipped;
  4. use Illuminate\Foundation\Testing\RefreshDatabase;
  5. use Illuminate\Foundation\Testing\WithoutMiddleware;
  6. use Illuminate\Support\Facades\Notification;
  7. use Tests\TestCase;
  8. class ExampleTest extends TestCase
  9. {
  10. public function test_orders_can_be_shipped()
  11. {
  12. Notification::fake();
  13. // Perform order shipping...
  14. // Assert that no notifications were sent...
  15. Notification::assertNothingSent();
  16. // Assert a notification was sent to the given users...
  17. Notification::assertSentTo(
  18. [$user], OrderShipped::class
  19. );
  20. // Assert a notification was not sent...
  21. Notification::assertNotSentTo(
  22. [$user], AnotherNotification::class
  23. );
  24. }
  25. }

You may pass a closure to the assertSentTo or assertNotSentTo methods in order to assert that a notification was sent that passes a given “truth test”. If at least one notification was sent that passes the given truth test then the assertion will be successful:

  1. Notification::assertSentTo(
  2. $user,
  3. function (OrderShipped $notification, $channels) use ($order) {
  4. return $notification->order->id === $order->id;
  5. }
  6. );

On-Demand Notifications

If the code you are testing sends on-demand notifications, you will need to assert that the notification was sent to an Illuminate\Notifications\AnonymousNotifiable instance:

  1. use Illuminate\Notifications\AnonymousNotifiable;
  2. Notification::assertSentTo(
  3. new AnonymousNotifiable, OrderShipped::class
  4. );

By passing a closure as the third argument to the notification assertion methods, you may determine if an on-demand notification was sent to the correct “route” address:

  1. Notification::assertSentTo(
  2. new AnonymousNotifiable,
  3. OrderShipped::class,
  4. function ($notification, $channels, $notifiable) use ($user) {
  5. return $notifiable->routes['mail'] === $user->email;
  6. }
  7. );

Queue Fake

You may use the Queue facade’s fake method to prevent queued jobs from being pushed to the queue. Most likely, it is sufficient to simply assert that Laravel was instructed to push a given job to the queue since the queued jobs themselves may be tested in another test class.

After calling the Queue facade’s fake method, you may then assert that the application attempted to push jobs to the queue:

  1. <?php
  2. namespace Tests\Feature;
  3. use App\Jobs\AnotherJob;
  4. use App\Jobs\FinalJob;
  5. use App\Jobs\ShipOrder;
  6. use Illuminate\Foundation\Testing\RefreshDatabase;
  7. use Illuminate\Foundation\Testing\WithoutMiddleware;
  8. use Illuminate\Support\Facades\Queue;
  9. use Tests\TestCase;
  10. class ExampleTest extends TestCase
  11. {
  12. public function test_orders_can_be_shipped()
  13. {
  14. Queue::fake();
  15. // Perform order shipping...
  16. // Assert that no jobs were pushed...
  17. Queue::assertNothingPushed();
  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. }
  25. }

You may pass a closure to the assertPushed or assertNotPushed methods in order to assert that a job was pushed that passes a given “truth test”. If at least one job was pushed that passes the given truth test then the assertion will be successful:

  1. Queue::assertPushed(function (ShipOrder $job) use ($order) {
  2. return $job->order->id === $order->id;
  3. });

Job Chains

The Queue facade’s assertPushedWithChain and assertPushedWithoutChain methods may be used to inspect the job chain of a pushed job. The assertPushedWithChain method accepts the primary job as its first argument and an array of chained jobs as its second argument:

  1. use App\Jobs\RecordShipment;
  2. use App\Jobs\ShipOrder;
  3. use App\Jobs\UpdateInventory;
  4. use Illuminate\Support\Facades\Queue;
  5. Queue::assertPushedWithChain(ShipOrder::class, [
  6. RecordShipment::class,
  7. UpdateInventory::class
  8. ]);

As you can see in the example above, the array of chained jobs may be an array of the job’s class names. However, you may also provide an array of actual job instances. When doing so, Laravel will ensure that the job instances are of the same class and have the same property values of the chained jobs dispatched by your application:

  1. Queue::assertPushedWithChain(ShipOrder::class, [
  2. new RecordShipment,
  3. new UpdateInventory,
  4. ]);

You may use the assertPushedWithoutChain method to assert that a job was pushed without a chain of jobs:

  1. Queue::assertPushedWithoutChain(ShipOrder::class);

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 Illuminate\Http\UploadedFile class, greatly simplifies the testing of file uploads. For example:

  1. <?php
  2. namespace Tests\Feature;
  3. use Illuminate\Foundation\Testing\RefreshDatabase;
  4. use Illuminate\Foundation\Testing\WithoutMiddleware;
  5. use Illuminate\Http\UploadedFile;
  6. use Illuminate\Support\Facades\Storage;
  7. use Tests\TestCase;
  8. class ExampleTest extends TestCase
  9. {
  10. public function test_albums_can_be_uploaded()
  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. }

For more information on testing file uploads, you may consult the HTTP testing documentation’s information on file uploads.

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

Interacting With Time

When testing, you may occasionally need to modify the time returned by helpers such as now or Illuminate\Support\Carbon::now(). Thankfully, Laravel’s base feature test class includes helpers that allow you to manipulate the current time:

  1. public function testTimeCanBeManipulated()
  2. {
  3. // Travel into the future...
  4. $this->travel(5)->milliseconds();
  5. $this->travel(5)->seconds();
  6. $this->travel(5)->minutes();
  7. $this->travel(5)->hours();
  8. $this->travel(5)->days();
  9. $this->travel(5)->weeks();
  10. $this->travel(5)->years();
  11. // Travel into the past...
  12. $this->travel(-5)->hours();
  13. // Travel to an explicit time...
  14. $this->travelTo(now()->subHours(6));
  15. // Return back to the present time...
  16. $this->travelBack();
  17. }