【问题标题】:Writing tests to verify received msg in jms listener (Spring-Boot)编写测试以验证在 jms 侦听器中收到的 msg (Spring-Boot)
【发布时间】:2017-03-15 07:37:23
【问题描述】:

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

  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

但这不是我所期望的。

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

感谢您的宝贵时间。

【问题讨论】:

    标签: spring-boot jms activemq spring-jms spring-test


    【解决方案1】:
    @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!");
        }
    
    }
    

    【讨论】:

    • 谢谢。虽然这适用于Queues,但不适用于我使用的activemq Topics。当我有属性spring.jms.pub-sub-domain=true 时不起作用。获取null
    • 这正是 JMS 主题的工作方式 - 默认情况下,订阅不是持久的,只有在发布消息时处于活动状态的消费者才能获得消息。您要么需要在发送之前等待侦听器订阅,要么使订阅持久(这意味着您只需在第一次运行测试时等待)。
    • 知道了!让它等待,它工作正常。再次感谢:)
    • 通常最好提出一个新问题而不是评论一个旧问题this answer 描述了我们为@RabbitListener 实施的一种技术,并解释了如何为@KafkaListener 实施它。同样的技术也应该通过自定义JmsListenerAnnotationBeanPostProcessor 应用于 JMS。
    • 对于 JUnit 5 替换 RunWith 规则,扩展名为 @ExtendWith(SpringExtension.class) (并从 org.springframework.boot:spring-boot-starter-test 中排除 junit4 dep )
    猜你喜欢
    • 1970-01-01
    • 2021-07-28
    • 2018-12-19
    • 1970-01-01
    • 2021-09-05
    • 2015-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多