vincent15000's avatar

How to use mock - Can you check my code ?

Hello,

It's the first time I try to use mocking.

Here is my code.

/** @test */
public function message_is_correctly_routed(): void
{
    $spy = $this->spy(CustomMessageHandler::class);

    $body = ... ; // some data

    (new MessageRouter)->handle($body);

    $spy->shouldHaveReceived('handle')->once()->with($body);
}

The body is passed to the handle method of the MessageRouter class which will route the message to the handle method of the CustomMessageHandler class (or another class according to the content of the body).

I want to check if the message is correctly routed, ie that the handle method from the CustomMessageHandler is called.

Is my code ok ?

It returns me false, whereas it should return me true.

I specify that the CustomMessageHandler isn't pass to the MessageHandler by dependency injection. Does mockery work in this situation ?

What do you suggest me ?

Thanks for your help.

V

0 likes
4 replies
s4muel's avatar

it does not work (imho) if you create the service directly (outside dependency injection/not pulling from app service container)

go to your MessageRouter and find the line which creates the CustomMessageHandler and try to pull it from service container

//instead
(new CustomMessageHandler::class)->...
//use
app(CustomMessageHandler::class)->...

of course add mandatory dependencies or bind it in the service container https://laravel.com/docs/11.x/container#binding

and it should work

1 like
s4muel's avatar
s4muel
Best Answer
Level 50

@vincent15000 it was just a concept, related to this point:

I specify that the CustomMessageHandler isn't pass to the MessageHandler by dependency injection. Does mockery work in this situation ?

it doesnt work, you must pass the CustomMessageHandler via service container/dependency injection. if you create it "manually" in MessageHandler like this (new CustomMessageHandler::class)->... the spy cant "hook" on it and spy on it. if you pull it out of service container app(CustomMessageHandler::class)->..., it could. (mind the app() helper https://laravel.com/docs/11.x/helpers#method-app)

if it is more complicated and CustomMessageHandler has a bunch of other dependencies, just prepare and register/bind it in the app service provider.

1 like

Please or to participate in this conversation.