Is it possible to mock protected properties and methods

Ilyes512 picture Ilyes512 · Aug 13, 2015 · Viewed 13.3k times · Source

Is it possible to mock a protected property with PHP Mockery?

I got a class with a method, I will call it `a, that does some magic on an array that is retrieved from a protected property from the same class.

That protected property is filled by another method b, in the same class.

I would like to test method a by mocking the protected property so I don't have to class method b first.

So is this possible? If not, should I refactor my code? Or are there other ways (considering best practises).

Answer

Fredrik Salin picture Fredrik Salin · Dec 1, 2015

It is possible to mock protected methods, but as some people have pointed out you might want to refactor your code if you feel the need for mocking these methods.

If you do want to mock protected methods you can do this according to the example below:

$myMock = Mockery::mock('myClass')->shouldAllowMockingProtectedMethods();

Using this mock it's then possible to mock protected methods in the same way as you would mock public methods.