如何模拟Spring Rabbitmq / amqp,以便在尝试自动创建交换/队列时在Spring Boot Test中不会失败?
鉴于我有一个简单的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?
最佳答案
这不是特别容易,如果代理不可用,我们通常使用JUnit @Rule
跳过测试。
但是,我们确实有很多使用模拟的测试,但是您确实必须了解很多Spring AMQP内部用法才能使用它们。您可以在project itself中探索测试用例。
有一次,我确实尝试编写一个模拟经纪人,但最终工作太多。
关于spring - 如何在 Spring 启动测试中模拟spring amqp/rabbit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38746522/