英文:
How to test SpringBoot JmsListener with JUnit
问题
以下是翻译好的部分:
"我想测试一个ActiveMQ消息传递(SpringBoot内存中)系统。我的问题是JUnit @Test
不允许方法带参数,但 @JmsListener
需要一个参数。我该如何测试这种情况?我也不知道如何使用JUnit的Parameterized.class来做到这一点?有没有一种方式可以在SpringBoot的@JmsListener
下运行测试?有人可以帮助我吗?
注意:mqSend.sendJson()
发送的是与代码片段中看到的相同的json字符串。
感谢建议。
@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));
}
请注意,代码中的HTML实体(例如"
)已被正确解析为双引号。
英文:
I want to test an ActiveMQ messaging (SpringBoot in-memory) system. My problem is that JUnit @Test
does not allow parameters for methods, but @JmsListener
needs a parameter. How can I test that case? I have also no clue how to do that with JUnit Parameterized.class? Is there a way to run the test with the SpringBoot @JmsListener
? Can anyone help me?
Note: The mqSend.sendJson(
) sends the same jsonString as you can see in the codesnippet.
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));
}
}
答案1
得分: -1
这里是一个示例,你需要使用 @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!");
}
}
英文:
Here an example, you have to @Autowire your JmsTemplate then use the methods you need to test :
@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!");
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论