Search code examples
javaspringtestingrabbitmqfunctional-testing

Is there an in memory messaging broker for functional testing of RabbitMq?


I need to write functional tests flows that involve interaction with RabbitMq. But once the tests are run I will have to clear any existing message in the queue. Since RabbitMq is persistent I need some in memory substitute for RabbitMq. Just like the way we have HSQL for databases.

I have tried using qpid broker but with no luck.

I am using spring boot framework. So I just need to inject the bean of the inmemory queue instead of actual rabbit mq.


Solution

  • Take a look at testcontainers. Running a RabbitMQ Docker image in such a test is very easy. It will be restarted for every test class or method, depending on how you use it.

    This will start a container running the rabbitmq:3.7 Docker image for the test class.

    public class AmqpReceiveServiceIntegrationTest {
    
      @ClassRule
      public static GenericContainer rabbitmqContainer =
        new GenericContainer<>("rabbitmq:3.7").withExposedPorts(5672);
    
      static ConnectionFactory factory;
      static Connection connection;
      static Channel sendChannel;
    
      @BeforeClass
      public static void beforeClass() throws IOException, TimeoutException {
        factory = new ConnectionFactory();
        factory.setHost(rabbitmqContainer.getContainerIpAddress());
        factory.setPort(rabbitmqContainer.getFirstMappedPort());
    
        connection = factory.newConnection();
    
        sendChannel = connection.createChannel();
        sendChannel.queueDeclare("hello", false, false, false, null);
      }
    
      @Test
      public void sendIsOk() {
        sendChannel.basicPublish("", "hello", null, "Hello World!.getBytes()); 
    
        // assertions ...
      }
    }