Search code examples
javajunitrabbitmqspring-boot-actuatorspring-rabbit

How to mock RabbitAdmin class in JUnit


I'm trying to create a mock object for RabbitAdmin class in JUnit.

@Mock RabbitAdmin rabbitAdmin; @InjectMocks MyOriginalClass classObj;

The above is what I have declared.

Mockito.when(rabbitAdmin.getQueueProperties("responseQueueName").get("QUEUE_MESSAGE_COUNT")).thenReturn(0);

When executing the above line in my test method I'm getting a NullPointerException.


Solution

  • Let me break down your mock call into pieces

    Mockito.when(
        rabbitAdmin.getQueueProperties("responseQueueName")
            .get("QUEUE_MESSAGE_COUNT")
    ).thenReturn(0);
    

    In the middle part, you have the following:

    rabbitAdmin.getQueueProperties("responseQueueName")
    

    rabbitAdmin itself is a mock object, that means every method has default behaviour to return null. If you have not specified any behavior for rabbitAdmin.getQueueProperties(anyString()) or rabbitAdmin.getQueueProperties("responseQueueName"), then this call will return null.

    Then you have the next part:

    rabbitAdmin.getQueueProperties("responseQueueName")
        .get("QUEUE_MESSAGE_COUNT")
    

    If you don't have any behaviour specified, then you are calling partically null.get("QUEUE_MESSAGE_COUNT") which will get you your NullPointerException.

    To avoid this null pointer, you could do something

    // creating a properties mock
    // this could also be a normal constructor call
    Properties properties = Mockito.mock(Properties.class);
    // returning 0 when QUEUE_MESSAGE_COUNT is called
    Mockito.when(properties.get("QUEUE_MESSAGE_COUNT")).thenReturn(0);
    
    // returning properties when responseQueueName is called
    Mockito.when(rabbitAdmin.getQueueProperties("responseQueueName")).thenReturn(properties);