Search code examples
javaspringspring-bootspring-jmsjmstemplate

why is JmsTemplate.receive method returning a null object?


I'm using Mockito to create a mock message object(inorder to test a ibmMqService) but jmsTemplate is returning a null

public class ImqMqServerTest {
    @InjectMocks
    IbmMqService ibmMqService;

    @Mock
    JmsTemplate jmsTemplate;

    @Value("${ibm.mq.queue.response}")
    String responseMq;

    void receiveOrderResponseTest() throws JMSException {
        jmsTemplate.send(responseMq, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                BytesMessage bytesMessage = session.createBytesMessage();
                String msg = "Test";                                                                                                                                                                                                                                         
                bytesMessage.writeBytes(msg.getBytes());
                return bytesMessage;
            }
        });

        Message message = jmsTemplate.receive(responseMq);
        System.out.println(message.getJMSMessageID()); 
    }
}

Solution

  • as Gary said, we need to stub the session createBytesMessage() method.

    You can use an anonymous class to initialize the BytesMessage interface.

    That initialization of ByteMessage interface can be given when the session mock createBytesMessage() method is called as below.

    @ExtendsWith(MockitoExtension.class)
    class Test {
        @Mock
        JmsSession session
       
        @Test
        void test() {
            BytesMessage message  = new BytesMessage() {
                // implementation 
            };
            doReturn(message).when(session).createBytesMessage();
            
            // Your Test
        }
    }