How to use Mockery in PHP

2 min readJul 17, 2022


I assume you have a basic understanding of the jargon and know what mocking is at least on theoretical level.

To be on the same page I would give you a naive and simplistic example to keep the ball rolling. Consider following example in which you have to use an API to get data.

You see the problem here?

Every time I run my test I have to hit the actual API which not only can slow down the test suit but can bring all the gazillion reasons why an API response can go wrong you know!

So it would be nice if we can eliminate the need to call the API again and again and supply mocked static API data instead. I hope you get the idea at this point as why we might want to use mocking.

For mocking in general there are various techniques which you can use to inject the data to account for the different dependencies; in our case it is TemperatureApi

Today I will give you a ten thousand feet view of a mocking library in PHP called Mockery which serves this very purpose of feeding mocked data at run time.

Okay, Let’s do some Mockery!

In an ideal world we always strive for ‘program to an interface not the concrete implementation’. Now update the code if you will like so:

Here you can see the advantage of using an interface; Our code is set up such a way so that we can utilise this to provide different implementations for the data; in our test case it’s being resolved against mocked object rather than hitting an actual API.

BUT! I don’t have the option to use Interfaces!!!

Initially I was sad too because I thought to myself what a waste of such a beautiful concept if I can’t use it without interfaces introduced in my code.

Mockery has this concept of Mocking Hard Dependencies through which you can overload the dependencies in-place as they occur; and YES it did blow my mind when I first sough them!

Consider following code:

And that’s it for the day!

Mocking your dependencies is useful technique to deal with side effects in your tests and hopefully by now you have some understanding of how to use it :-)

Happy Mocking!