Search code examples
springspring-testspring-amqpspring-rabbit

how to mock spring amqp/rabbit in spring boot test


How to mock spring rabbitmq/amqp so it will not fail during a Spring Boot Test while trying to auto create exchanges/queues?

Given I have a simple RabbitListener that will cause the queue and exchange to be auto created like this:

@Component
@RabbitListener(bindings = {
        @QueueBinding(
                value = @Queue(value = "myqueue", autoDelete = "true"), 
                exchange = @Exchange(value = "myexchange", autoDelete = "true", type = "direct"), 
                key = "mykey")}
)
@RabbitListenerCondition
public class EventHandler {
    @RabbitHandler
    public void onEvent(Event event) {
      ...
    }   
}

During a simple Spring Boot Test, like this:

@ActiveProfiles("test")
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = { Application.class })

    @Autowired
    private ApplicationContext applicationContext;

    @Test
    public void test() {
        assertNotNull(applicationContext);
    }

}

it will fail with:

16:22:16.527 [SimpleAsyncTaskExecutor-1] ERROR o.s.a.r.l.SimpleMessageListenerContainer - Failed to check/redeclare auto-delete queue(s).
org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused
    at org.springframework.amqp.rabbit.support.RabbitExceptionTranslator.convertRabbitAccessException(RabbitExceptionTranslator.java:62)
    at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:309)

In in this test I don't care about Rabbit/AMQP, so how can I mock the whole Rabbit/AMQP away?


Solution

  • It's not particularly easy, we generally use a JUnit @Rule to skip the test if the broker's not available.

    However, we do have a lot of tests that use mocks, but you really have to understand a lot of the Spring AMQP internals to use them. You can explore the test cases in the project itself.

    At one point I did attempt writing a mock broker but it ended up being too much work.