Skip to main content
 首页 » 编程设计

spring-boot之编写测试来验证 jms 监听器中收到的消息(Spring-Boot)

2024年05月29日49tuyile006

我想为如下内容编写测试;

  1. src/main中有一个名为state-info-1的监听器。

  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 
} 

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

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

但这不是我所期待的。

任何帮助或插入正确的方向就足够了。

感谢您的宝贵时间。

请您参考如下方法:

@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()); 
    } 
 
} 

@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!"); 
    } 
 
}