2

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()); 
    }
}
Dmitry Rakovets
  • 557
  • 1
  • 6
  • 15
Thivya Thogesan
  • 206
  • 2
  • 12
  • you mean `jmsTemplate` is `null` or `jmsTemplate.receive(responseMq)` returns `null`? – pleft Oct 25 '21 at 17:19
  • 1
    That is the default behavior of mocks - you have to tell Mockito what to do when each method is called (it's called stubbing). – Gary Russell Oct 25 '21 at 17:23
  • 1
    Why shouldn't it return `null`? You are using a mock `JmsTemplate`. The default behavior of a mock is to return `null` when nothing is registered for that method. Your `send` method, doesn't do anything either (as that is called on the same mock as well). – M. Deinum Oct 27 '21 at 11:22

2 Answers2

2

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
    }
}
Dmitry Rakovets
  • 557
  • 1
  • 6
  • 15
Sivaram Rasathurai
  • 5,533
  • 3
  • 22
  • 45
0

File does not seem to be declared as a Spring bean anywhere. Add the @Service annotation on it. and

@Autowired JmsTemplate jmsTemplate