Search code examples
phplaravelmockingphpunitlaravel-9

Method should be called exactly 1 times but called 0 times


Test example:

$mock = $this->mock(GetAll::class);
$mock->shouldReceive('setCustomersQueryParametersDto')
     ->once()
     ->with($customerDto)
     ->andReturnSelf();

$mock->shouldReceive('execute')->once()->andReturn(collect([])); 

$this->actingAs($user)->json('GET', $this->generateUrl());

How does it work? I have class GetAll and that class has a setter (setCustomersQueryParametersDto) before the execute method call, I need to set my DTO class which I did first. And then I expected when running the test, that everything should be fine, but in my controller response from execute method is wrong.

Code in controller:

$this->getAllAction->setCustomersQueryParametersDto($customersRequest->model())->execute();

Solution

  • I didn't solve a problem that I had. It is still a mystery to me why Mockery can't execute previous code. But because I only need results from execute method, I find work around with this piece of code:

    $getAllMock->shouldReceive('setCustomersQueryParametersDto->execute')
               ->andReturn($results);
    

    (Chain methods in Mockery documentation: http://docs.mockery.io/en/latest/reference/demeter_chains.html)

    So I didn't have to bother about fields in GetAll::Class, I simply returned results and that's it. But in this case, it works, in some more complex examples, I will probably need to set a field, so it will be tricky.....