vincent15000's avatar

How to test a code depending on messages coming from RabbitMQ ?

Hello,

I have an application with a command to consume messages coming from RabbitMQ.

How it works ? I send a message to RabbitMQ and a microservice responds back sending me a message.

Unit tests work fine.

Now I want to write feature tests.

backend sends message to RabbitMQ via a controller RabbitMQ answers => how to simulate this step with mock ?

I have written this code after the API request in the test, but it seems not to work.

$this->mock(MyService::class, function (MockInterface $mock) {
    $mock->shouldReceive([
		// payload
    ])->once();
});

Thanks for your help.

V

0 likes
2 replies
mabdullahsari's avatar
Level 16

This way of approaching the problem is too brittle. You should create a logical boundary within your application that represents the authority of this microservice and convert the incoming messages to events or commands within your logical boundary which in their turn get dispatched using the regular Bus / Event Dispatchers.

This way, you can then just dispatch the command/event using Bus/Event::dispatch and then assert the outcome. Long story short, decouple the delivery mechanism from the actual implementation of the logical boundary.

Pseudocode:

final class ProcessIncomingEventMessage extends Job
{
    public function handle(Dispatcher $dispatcher, EventDeserializer $event): void
    {
        $dispatcher->dispatch(
            $event->deserialize($this->rabbitMessage->getAttribute('event'))
        );
    }
}
1 like

Please or to participate in this conversation.