You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多Testcontainers测试类场景下ActiveMQ Broker配置连接失败问题求助

多Testcontainers测试类场景下ActiveMQ Broker配置连接失败问题求助

我最近在搭建基于Testcontainers的ActiveMQ集成测试环境,单个测试类运行完全正常,但只要同时存在两个测试类,就会出现连接拒绝的错误,实在搞不懂哪里出问题了,来请教下大家!

先给大家看我的代码结构:

基础测试基类(所有测试类继承它)

@SpringBootTest
@ActiveProfiles("test")
abstract class BaseIntegrationTest {
    companion object {
        @JvmStatic
        val activeMQContainer: GenericContainer<*> = GenericContainer("rmohr/activemq:5.15.9")
            .withExposedPorts(61616)
            .waitingFor(Wait.forListeningPort())

        @JvmStatic
        @BeforeAll
        fun setup() {
            activeMQContainer.start()
            System.setProperty(
                "jms.activemq.brokerUrl",
                "tcp://${activeMQContainer.host}:${activeMQContainer.getMappedPort(61616)}"
            )
        }

        @JvmStatic
        @AfterAll
        fun tearDown() {
            activeMQContainer.stop()
        }
    }
}

测试环境的JMS配置类

@Configuration
@Profile("test")
class TestJmsConfig(
    @Value("\${jms.activemq.brokerUrl}") private val brokerUrl: String
) {
    @Bean
    fun connectionFactory(): ConnectionFactory {
        return ActiveMQConnectionFactory().apply {
            brokerURL = brokerUrl
        }
    }

    @Bean
    fun jmsTemplate(connectionFactory: ConnectionFactory): JmsTemplate {
        return JmsTemplate(connectionFactory)
    }
}

测试类示例

我写了两个类似的测试类,比如下面这个:

@SpringBootTest
@AutoConfigureMockMvc
class NiceControllerIntegrationTest : BaseIntegrationTest() {

    @Autowired
    lateinit var mockMvc: MockMvc

    @Test
    fun `send nice message`() {
        mockMvc.perform(MockMvcRequestBuilders.post("/v1/nice/send"))
    }
}

调用这个接口会触发向ActiveMQ队列发送消息的逻辑。

问题现象

  • 只保留一个测试类时,测试能顺利通过,消息也能正常发送到队列;
  • 同时存在两个测试类时,就会抛出连接失败的异常,关键错误信息如下:
jakarta.servlet.ServletException: Request processing failed: org.springframework.jms.UncategorizedJmsException: Uncategorized exception occurred during JMS processing
...
Caused by: jakarta.jms.JMSException: Could not connect to broker URL: tcp://localhost:32769. Reason: java.net.ConnectException: Connection refused
...

我的依赖版本

  • Spring Boot 3.2.5
  • Java 21
  • Kotlin 2.0.0

有没有大佬能帮我分析下问题出在哪?或者有没有什么优化的方案?

备注:内容来源于stack exchange,提问作者nietup

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.15 10:49:36