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.
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:
Now our question is what actually happens when
mock() methods is called?
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
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.