Unit test on rabbitMQ

I have an application that publishes an event for RabbitMQ and a consumer that consumes the event. My question is, is there a way to write unit test to test the functionality of this consumer.

To add this, the consumer works more in a hierarchical structure, i.e. when placing an order event, the subregions are retrieved in it and sent their corresponding events to the queue when the subtasks are consumed, the lines in each of them are also sent to the queue, and finally, details for each lineItem object will be sent to.

Thanks for your help in advance.

+7
java unit-testing rabbitmq
source share
2 answers

It seems that the path to an easy-to-use solution for testing development related to RabbitMQ is still a long way off.

See this discussion and this discussion from the SpringFramework forum. They either use Mockito (for unit tests) or a real instance of RabbitMQ (integration tests) for their own testing.

Also, see this post, where the author uses a real RabbitMQ byte with some features to make this a more "test-friendly" task. However, at the moment the solution is valid only for MAC users!

+3
source share

Continuing with the previous answer, here is a very fast implementation for the unit test route (using Mockito). The starting point is one of RabbitMQ's own lessons for java.

Receiver class (message handler)

public class LocalConsumer extends DefaultConsumer { private Channel channel; private Logger log; // manual dependency injection public LocalConsumer(Channel channel, Logger logger) { super(channel); this.log = logger; } @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); // insert here whatever logic is needed, using whatever service you injected - in this case it is a simple logger. log.print(" [x] Received and processed '" + message + "'"); } } 

Testing class

 public class LocalConsumerTest { Logger mockLogger = mock(Logger.class); Channel mockChannel = mock(Channel.class); String mockConsumerTag = "mockConsumerTag"; LocalConsumer _sut = new LocalConsumer(mockChannel, mockLogger); @Test public void shouldPrintOutTheMessage () throws java.io.IOException { // arrange String message = "Test"; // act _sut.handleDelivery(mockConsumerTag, null, new AMQP.BasicProperties(), message.getBytes() ); // assert String expected = " [x] Received and processed '" + message + "'"; verify(mockLogger).print(eq(expected)); } } 

Consumer

  // ... // this is where you inject the system you'll mock in the tests. Consumer consumer = new LocalConsumer(channel, _log); boolean autoAck = false; channel.basicConsume(queueName, autoAck, consumer); // ... 
0
source share

All Articles