Laravel Facades and Mockery, testing chained methods
🤔 How this happened
I was trying to play with PHPUnit and Laravel. And I had this need to test Laravel Facades. Those were using a chained method.
So, after this, my tests failed because it says that it can execute put on null . That meant, for some reason, the disk method was returning null, which I know wasn’t true.
After some research. I found in the Mockery documentation (wich is what Laravel is using), that you need to specify to Mockery what’s returning your mocked function. In the following line, if I don’t set the return, it will be null by default. And will cause next assertions to fail.
The solution to this comes from a simple method from Mockery
andReturnSelf . Notice this depends on your class implementation, but the majority of chained methods would return the class by itself. Otherwise, you can use
andReturn and write the object, string, array or data structure that the Mock will return.
For this specific case, I needed
andReturnSelf . Let’s see how the final result works. To test it, my
ChainController is connected to the
POST /chain route.
You can see a working example, click here