使用spring-rabbit-test进行Junit测试

4
我试图编写一个rabbitMq监听器的测试用例。我尝试使用spring-rabbit-test,但在运行测试时出现以下错误:
"Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2018-03-06 17:10:50.113 ERROR 14239 --- [ main] o.s.boot.SpringApplication: Application run failed java.lang.IllegalStateException: Another endpoint is already registered with id 'response_queue' at org.springframework.util.Assert.state(Assert.java:73) ~[spring-core-5.0.4.RELEASE.jar:5.0.4.RELEASE] at org.springframework.amqp.rabbit.listener.RabbitListenerEndpointRegistry.registerListenerContainer(RabbitListenerEndpointRegistry.java:151) ~[spring-rabbit-2.0.2.RELEASE.jar:2.0.2.RELEASE]"
我正在按照[https://docs.spring.io/spring-amqp/reference/htmlsingle/#testing]中提供的示例进行操作,在理想情况下,它不需要为侦听器添加@Component。

现在我的测试类也试图获取侦听器结果,导致了上述错误。

有人可以帮助我吗?

测试配置

@Configuration    
@RabbitListenerTest
public class RabbitMQTestConfig {
    @Autowired
    MyListener myListener;
}

测试

@ActiveProfiles("test")
@RunWith(SpringRunner.class)
@SpringBootTest
public class RabbitMQTest {

    @Rule
    public BrokerRunning brokerRunning = BrokerRunning.isRunning();

    @Autowired
    private RabbitListenerTestHarness harness;

    @Test
    public void testMyListener() {

    }

}

监听器

@Component
public class MyListener {

@Autowired
MyService myService;


@RabbitListener(id = "response_queue", queues = "response")
    public void processOrder(SomeResponse someResponse) {
        myService.process(someResponse);
    }
}
2个回答

3

好的...您需要与我们分享您的项目。这是一个简单的变体,让我们重现和玩耍以确定原因。

现在我无法使用非常简单的Spring Boot应用程序进行重现:

@SpringBootApplication
public class So49129095Application {

    public static void main(String[] args) {
        SpringApplication.run(So49129095Application.class, args);
    }
}

@Component
public class MyListener {

    @RabbitListener(id = "response_queue", queuesToDeclare = @Queue("response"))
    public void processOrder(Object payload) {

    }

}

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {So49129095Application.class, So49129095ApplicationTests.RabbitMQTestConfig.class})
public class So49129095ApplicationTests {

    @Rule
    public BrokerRunning brokerRunning = BrokerRunning.isRunning();

    @Autowired
    private RabbitListenerTestHarness harness;

    @Test
    public void testMyListener() {

    }

    @Configuration
    @RabbitListenerTest
    public static class RabbitMQTestConfig {

        @Autowired
        MyListener myListener;

    }

}

对我来说,似乎我没有错过如何将所有内容配置在一起的任何要点。


0

当您使用相同的ID注册2个侦听器时,就会发生这种情况。

很可能您有一个定义了侦听器的类,然后手动创建了另一个相同类的bean(可能是模拟的)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接