Search code examples
phpmockery

Pass parameters into a mocked class' constructor in PHP/Mockery


This feels simple but the answer is eluding me behind internet pages and questions/answers, some of which I'm not confident enough to consider definitive.

My requirement is simple. I have a PHP class ActionRequestService which has two parameters. I would normally instantiate it:

$actionRequestService = new ActionRequestService($param1, $param2);

I'm mocking like:

$actionRequestServiceMock = Mockery::mock(ActionRequestService::class);

My question is, how do I get my parameters $param1 and $param2 into the class?

This is legacy code so cannot be changed and I need to achieve code coverage by writing more tests.


Solution

  • You need to pass the parameters intended for the constructor as an array in the second parameter:

    $actionRequestServiceMock = Mockery::mock(ActionRequestService::class, [
            $param1, $param2]);