【问题标题】:Mock connection to RabbitMQ与 RabbitMQ 的模拟连接
【发布时间】:2020-02-28 14:19:39
【问题描述】:

我有一个带有 Spring AMQP 的 Spring 应用程序。我想运行 JUnit 测试,它使用 H2 数据库启动 Spring。

但是对于 Spring AMQP,我在启动时遇到了这个异常:

 Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.amqp.core.AmqpAdmin]: Factory method 'amqpAdmin' threw exception; nested exception is org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:640)
        ... 83 common frames omitted
    Caused by: org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect

有什么方法可以模拟到 RabbitMQ 的连接吗?

【问题讨论】:

    标签: java spring junit spring-amqp junit5


    【解决方案1】:

    RabbitMQ-mock 库可能会有所帮助,它模拟 ConnectionFactory 以提供模拟连接。可以在here 找到一个集成测试的工作示例。

    【讨论】:

    • 也许我需要在 application.properties 文件中设置连接属性?
    【解决方案2】:

    您可以在测试中使用 apache qpid https://qpid.apache.org/ 作为模拟 只需在测试上下文中创建 Broker

    private final Broker broker = new Broker();
    public EmbeddedAMQPBroker() throws Exception {
        final String configFileName = "qpid-config.json";
        final String passwordFileName = "passwd.properties";
        // prepare options
        final BrokerOptions brokerOptions = new BrokerOptions();
        brokerOptions.setConfigProperty("qpid.amqp_port", String.valueOf(BROKER_PORT));
        brokerOptions.setConfigProperty("qpid.pass_file", findResourcePath(passwordFileName));
        brokerOptions.setConfigProperty("qpid.work_dir", Files.createTempDir().getAbsolutePath());
        brokerOptions.setInitialConfigurationLocation(findResourcePath(configFileName));
        // start broker
        broker.startup(brokerOptions);
    }
    

    它将构建您的本地 AMQP 消息代理,您可以在没有 RabbitMQ 环境的情况下使用它

    或者如果您只想模拟对象而不提供功能,您可以使用 Mockito 框架

    【讨论】:

    • 最好的选择是使用测试容器
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    • 2016-11-14
    相关资源
    最近更新 更多