Mockery, Magic Methods and Laravel Models
It is true that you can’t mock a magic method, but you can mock the underlying logic that is in said magic method - __call
, __get
, or __set
Using mockery in your unit tests in your Laravel application is possible because Laravel simply calls getAttribute
or setAttribute
, which can easily be mocked.
If your magic method handles all the logic directly then, this will present a problem. But you can move it to its own protected method and call that method in the magic method instead which then will allow you to mock that new protected method.
Here is an example of mocking a property on a Laravel model
$mock->shouldReceive('getAttribute')
->with($property)
->andReturn($propertyValue);
Tip If you are only relying on a single property in your test then you can opt out of the ->with($property)
method call, but using it is more descriptive so that’s what I’ll be doing moving forward.