如何等待@JMSListener注释方法在JUnit中完成 [英] How to wait for @JMSListener annotated method to complete in JUnit

查看:171
本文介绍了如何等待@JMSListener注释方法在JUnit中完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在尝试对JMS处理(基于Spring(v4.1.6)的代码)进行一些集成测试.

So I am trying to get some integration testing of JMS processing, Spring (v4.1.6) based code.

这是一个非常标准的Spring设置,带有@JmsListener注释方法,而DefaultMessageListenerContainerconcurrency设置为1,因此只允许一个侦听线程.

It's a very standard Spring setup with @JmsListener annotated method and a DefaultMessageListenerContainer with concurrency set to 1 and therefore allowing only 1 listening thread.

现在,我利用ActiveMQ的嵌入式代理不依赖任何外部jms代理来使测试随时随地运行(我应该从事市场营销工作).

Now, I leveraged ActiveMQ's embedded broker not to rely on any external jms broker for the tests to run anywhere anytime (I should work in marketing).

所有接线都很好,然后我进行了JUnit测试:

So it all wires fine and then I have my JUnit test:

@Test
public void test() {
    sendSomeMessage();
    //how to wait here for the @JMSListener method to complete
    verify();
}

我发送了消息,但是随后我需要以某种方式等待@JMSListener带注释的方法完成.我该怎么做?

I send the message, but then I need to somehow wait for the @JMSListener annotated method to complete. How do I do this?

推荐答案

好吧,我希望我可以以某种方式挂接到Message Driven Pojos生命周期中,以实现此目的,但是通过其他有关异步代码的问题,我想到了基于CountDownLatch

Well, I was hoping I can somehow hook into the Message Driven Pojos lifecycle to do this, but going through other SO questions about async code I came up with a solution based on CountDownLatch

  1. 所有工作完成后,带有注释的@JMSListener方法应在CountDownLatch上调用countDown():

  1. The @JMSListener annotaded method should call countDown() on a CountDownLatch after all the work is complete:

@JmsListener(destination = "dest", containerFactory = "cf")
public void processMessage(TextMessage message) throws JMSException {
    //do the actual processing
    actualProcessing(message);
    //if there's countDownLatch call the countdown.
    if(countDownLatch != null) {
        countDownLatch.countDown();
    }
}

  • 在testMethod中

  • In the testMethod

    @Test
    public void test() throws InterruptedException {
        //initialize the countDownLatch and set in on the processing class
        CountDownLatch countDownLatch = new CountDownLatch(1);
        messageProcessor.setCountDownLatch(countDownLatch);
        //sendthemessage
        sendSomeMessage();
        //wait for the processing method to call countdown()
        countDownLatch.await();
        verify();
    }
    

  • 该解决方案的缺点是您必须专门针对集成测试更改@JMSListener带注释的方法

    The drawback of this solution is that you have to actually change your @JMSListener annotated method specifically for the integration test

    这篇关于如何等待@JMSListener注释方法在JUnit中完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆