简体   繁体   English

如何使用 JUnit 测试 SpringBoot JmsListener

[英]How to test SpringBoot JmsListener with JUnit

I want to test an ActiveMQ messaging (SpringBoot in-memory) system.我想测试一个 ActiveMQ 消息传递(SpringBoot in-memory)系统。 My problem is that JUnit @Test does not allow parameters for methods, but @JmsListener needs a parameter.我的问题是 JUnit @Test不允许方法的参数,但@JmsListener需要一个参数。 How can I test that case?我该如何测试这种情况? I have also no clue how to do that with JUnit Parameterized.class?我也不知道如何使用 JUnit Parameterized.class 来做到这一点? Is there a way to run the test with the SpringBoot @JmsListener ?有没有办法使用 SpringBoot @JmsListener运行测试? Can anyone help me?谁能帮我?

Note: The mqSend.sendJson( ) sends the same jsonString as you can see in the codesnippet.注意: mqSend.sendJson( ) 发送的 jsonString 与您在代码片段中看到的相同。

Thank's for advice.谢谢你的建议。

@Autowired
private MqSend mqSend;

@MockBean
private JmsTemplate jmsTemplate;

private String jsonString = "{ \"Number\": \"123456\", \"eMail\": \"mail@dummy.de\", \"Action\": \"add\" }";
private String receivedMessage;

@Before
public void setup() throws IOException {
    this.mqSend.sendJson();
    log.info("Setup done");
}

@Test
@JmsListener(destination = "${jms.queue}")
private void receiveMessageFromMQ(String message) {
    this.receivedMessage = message;
    log.info("Received Message: " + message);
}

@Test
public void test_sending_and_receiving_messages() {
    Assert.assertTrue(this.receivedMessage.equals(this.jsonString));
}

} }

Here an example, you have to @Autowire your JmsTemplate then use the methods you need to test:这是一个示例,您必须 @Autowire 您的 JmsTemplate 然后使用您需要测试的方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM