How to test SpringBoot JmsListener with JUnit

Viewed 6527

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 Answers

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