Tuesday, 28 November 2017

How do I mock or simulate a message queue in JMS?


"I have a test message, which format and content I already know. I also have the Java class that parses and reads this message. In real world, this message will come from a JMS message queue. I would like to simulate, mock or generate a message queue on my local PC for testing purposes. How do I mock it?" (source)


To test an application in isolation when the real production JMS provider is not available you can use one of:
  1. JMS mock: When testing your applications you can simulate the non-existing dependencies using test doubles. You can use a JMS mock which will simulate the behaviour of a real JMS provider. You can create a JMS mock using Traffic Parrot. Using a JMS mock will allow you for a high level of flexibility during testing. You will be able to test typical production-like test scenarios but also hypothetical situations by setting up your mock to return almost any type of message. You will also be able to simulate different types of errors, which is often hard to do with real JMS providers. Have a look at this introduction video to JMS service virtualization for ActiveMq (service virtualization is a different name for a mock) or this one for IBM MQ.
  2. JMS provider test instance: You can run a JMS provider on your laptop or in one of your test environments and connect your application to it instead of the production provider. When you use open source providers in production like ActiveMQ or RabbitMQ, it should be easy to run one of them on your laptop as well because they are lightweight and free. For IBM Websphere MQ, you can use the free IBM MQ for Developers
  3. JMS class mock: You can use Mockito in unit tests to mock interactions with JMS classes. This solution comes with all the trade-offs of unit testing. For more information on those see testing pyramid. If you would like to black box test your application, use one of the solutions I have described above. 

If you have any more questions or need help with creating your first JMS mock, schedule a free 30-minute consultation call with our consultants today.