How Mockery Interacts with Laravel Service Container

2 min readMar 28, 2021

When testing Laravel applications, you may wish to “mock” certain aspects of your application so they are not actually executed during a given test.


Instructing the Laravel IOC container to use our mocked instance of the object instead of constructing a real object of a class.


We need a bridge between Mockery and Laravel Service Container.


In vendor directory Laravel > Framework > Src > Illuminate > Foundation > Testing > Concerns there are some traits.

If you have a look at the trait InteractsWithContainer.php you will see this trait is responsible for mocking an instance of an object in the container.

When in your test classes you call mock() method, behind the scene Laravel refers the method in this trait.

As an example, in Laravel Fortify there are some tests, let’s look at one of them as below:

A test case in Laravel/Fortify

Now our question is what actually happens when mock() methods is called?

This mock() method calls the instance() method. Let’s have a look at the it.

Note: Above you see a Mockery instance of the object is what we are passing to the instance() method.

As you see below the instance() method is itself responsible for calling the primary instance() method on app which is the instance of the Laravel IOC Container.


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 and not a real instance.

I would like to introduce Laravel Pay Pocket which I have developed it recently.