编写测试以验证jms侦听器中收到的消息(Spring-Boot)

Raj*_*ami 6 activemq-classic jms spring-test spring-jms spring-boot

我想写下面的测试;

  1. 有一个叫听者state-info-1src/main.

  2. 它对它获得的任何消息进行一些更改,并在activemq主题上发布新消息state-info-2.

  3. 我将构建一个虚拟消息并发布到activemq主题state-info-1.

  4. 最后验证,收到的关于主题的消息state-info-2就像我预期的那样.

我的听众就像;

@JmsListener(destination = "state-info-1", containerFactory = "connFactory")
public void receiveMessage(Message payload) {
    // Do Stuff and Publish to state-info-2
}
Run Code Online (Sandbox Code Playgroud)

我可以为此写测试吗?或者我必须以其他方式做到这一点?

另外,我看了这个:https://github.com/spring-projects/spring-boot/blob/master/spring-boot-samples/spring-boot-sample-activemq/src/test/java/sample/activemq /SampleActiveMqTests.java

但这不是我所期待的.

任何帮助或推动正确的方向就足够了.

感谢您的时间.

Gar*_*ell 10

@SpringBootApplication
public class So42803627Application {

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

    @Autowired
    private JmsTemplate jmsTemplate;

    @JmsListener(destination = "foo")
    public void handle(String in) {
        this.jmsTemplate.convertAndSend("bar", in.toUpperCase());
    }

}
Run Code Online (Sandbox Code Playgroud)

@RunWith(SpringRunner.class)
@SpringBootTest
public class So42803627ApplicationTests {

    @Autowired
    private JmsTemplate jmsTemplate;

    @Test
    public void test() {
        this.jmsTemplate.convertAndSend("foo", "Hello, world!");
        this.jmsTemplate.setReceiveTimeout(10_000);
        assertThat(this.jmsTemplate.receiveAndConvert("bar")).isEqualTo("HELLO, WORLD!");
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 这就是JMS主题的工作方式 - 默认情况下,订阅不是持久的,只有那些在发布消息时处于活动状态的消费者才能获得消息.您需要在发送之前等待侦听器订阅,或者使订阅持久(这意味着您只需要在第一次运行测试时等待). (2认同)
  • 对于 **JUnit 5** 替换 `RunWith` 规则,扩展名为 `@ExtendWith(SpringExtension.class)`(并从 org.springframework.boot:spring-boot-starter-test 中排除 junit4 dep) (2认同)