如何模拟 spring rabbitmq/amqp,以便它在尝试自动创建交换/队列时不会在 Spring Boot 测试期间失败?
鉴于我有一个简单的 RabbitListener
这将导致队列和交换像这样自动创建:
@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) {
...
}
}
在一个简单的 Spring Boot 测试中,像这样:
@ActiveProfiles("test")
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = { Application.class })
@Autowired
private ApplicationContext applicationContext;
@Test
public void test() {
assertNotNull(applicationContext);
}
}
它会失败:
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)
在此测试中,我不关心 Rabbit/AMQP,那么如何模拟整个 Rabbit/AMQP?
原文由 domi 发布,翻译遵循 CC BY-SA 4.0 许可协议
这不是特别容易,如果代理不可用,我们通常使用 JUnit
@Rule
跳过测试。然而,我们确实有很多使用模拟的测试,但你真的必须了解很多 Spring AMQP 内部才能使用它们。您可以探索 项目本身 的测试用例。
有一次我确实尝试编写一个模拟经纪人,但最终工作量太大了。