0

I cannot mock jms queue TextMessage for testing JMSException tried mulitple ways but seems like i am not understanding it. any help is appreciated.

It seems like i cannot properly mock and utilize Message object.

Source code:

    public class ConsumeService {
    
      private DataProcessService dataProcessService;
    
    @JmsListener
      public void getMessage(final Message message) throws InterruptedException {
    
        if (message instanceof TextMessage) {
          TextMessage message = (TextMessage) message;
          try {
            
    
            dataProcessService.processRequestData(
                message.getText(), prepareInfo(message));
            
    
          } catch (JMSException e) {
            log.error("JMSException in message");
          } catch (ResourceAccessException e) {
            log.error("IOException in message");
          }
        } else {
          log.error("message convertion failed!");
        }
      }
     }

Unit test code:

    @InjectMocks ConsumeService consumeService;
    
    @Mock DataProcessService dataProcessService;
    
    @Test
      public void testException() throws ResourceAccessException, JMSException{
    
        TextMessage message = mock(TextMessage.class);
        
        Mockito.lenient()
        .when(
            dataProcessService.processRequestData(
                    ((TextMessage) message).getText(), prepareInfo((TextMessage) message)))
        .thenThrow(JMSException.class);
        
        assertThrows(
                JMSException.class,
                () -> this.consumeService.getMessage(message));
      }
    
    private Map<String, String> prepareInfo(TextMessage mqMessage) throws JMSException {
    
        ..
        ..
        
      }

Error:

org.mockito.exceptions.base.MockitoException: 
Checked exception is invalid for this method!
Alexander van Oostenrijk
  • 4,644
  • 3
  • 23
  • 37
Reese
  • 389
  • 2
  • 10
  • 26
  • 1
    Maybe this answers your question: https://stackoverflow.com/questions/3762047/throw-checked-exceptions-from-mocks-with-mockito – Georgii Lvov Jul 23 '21 at 20:23
  • thank you .. i understood where i gone wrong. But now how to mock this dataProcessService.processRequestData( ((TextMessage) message).getText(), prepareInfo((TextMessage) message))) method, i am not understanding how to mock prepareInfo method output inside a method. can you please help – Reese Jul 24 '21 at 18:56
  • should i create a separate question for this? – Reese Jul 24 '21 at 20:40
  • I see that `prepareInfo` method is in the test class, why do you want to mock it? – Georgii Lvov Jul 24 '21 at 20:47
  • i have created a seperate issue for that. Request you to please have a look once. https://stackoverflow.com/questions/68513813/org-mockito-exceptions-misusing-missingmethodinvocationexception-cannot-test-e – Reese Jul 24 '21 at 21:07

0 Answers0