How Mockery Interacts with Laravel Service Container

Panjeh
2 min readMar 28, 2021

--

Before you start this tutorial, I would like to introduce two packages for Laravel that I have recently developed: Laravel Pay Pocket, a modern multi-wallet package, and Laravel Failed Jobs, a UI for the Laravel Failed Jobs Table. I hope they may be of help to you.

https://github.com/HPWebdeveloper/laravel-pay-pocket
https://github.com/HPWebdeveloper/laravel-failed-jobs

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

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

Goal:

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

How:

We need a bridge between Mockery and Laravel Service Container.

Description:

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.

Briefly:

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.

--

--

Panjeh
Panjeh

Written by Panjeh

Posting about Python and Laravel

No responses yet