3

I am trying to test the RabbitTemplate#convertAndSend method that is written as a lambda, like so:

// other stuff omitted for brevity

        rabbitTemplate.convertAndSend(myQueue, jsonString, message -> {
        message.getMessageProperties().setPriority(priority);
        return message;
        });

// other stuff omitted for brevity

The test case I am trying to do is one where an ArgumentCaptor is being used in order to verify that the method is called with correct parameters.

@Test
public void givenMyNotification_whenElementIsSent_thenSetPriorityAndSendValidParameters() {

final ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
final int expectedPriority = 5;
final Notification expected = TestUtils.getNotification();

testClass.handleNotification(expected);

verify(rabbitTemplate).convertAndSend(captor.capture(), captor.capture(),
    ArgumentMatchers.eq(MessagePostProcessor.class));

// assertThat...
));

}

The test fails at the verify step because the arguments are different.

Wanted:
<Capturing argument>,
<Capturing argument>,
interface org.springframework.amqp.core.MessagePostProcessor

Actual invocation:
"myQueue",
"myJson",
com.example.notification.service.NotificationService$$Lambda$5/73698537@5bda80bf

I have tried several other Matchers from mockito and hamcrest but to no avail.

So, my questions are:

  1. How does one test this kind of a thing?

  2. Is this even a good practice or are there other/better ways to test rabbit template sending?

3 Answers 3

2

You almost get it all right, except for the last matcher ArgumentMatchers.eq(MessagePostProcessor.class).

You actually ask Mockito to match for equatility to the class of the parameter. You should rather match against:

  • the type of the parameter using ArgumentMatchers.any(MessagePostProcessor.class)
  • or an actual value ArgumentMatchers.eq(expectedMessageProcessor) if you happen to have it
  • or an argument captor if you do need to check the value of the parameter

In this particular case however, if you use the first option, you may run into a compiler issue, as RabbitTemplate class has two similar methods:

  • convertAndSend(String, String, Object)
  • convertAndSend(String, Object, MessagePostProcessor)

To solve this you can force the type of the second parameter to object like this :

Mockito.verify(rabbitTemplate).convertAndSend(captor.capture(), (Object) captor.capture(),
            Mockito.any(MessagePostProcessor.class));

Or better, have two different ArgumentCaptors for two different parameters:

ArgumentCaptor<String> routingKeyCaptor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<Object> messageCaptor = ArgumentCaptor.forClass(Object.class);

...

verify(rabbitTemplate).convertAndSend(routingKeyCaptor.capture(), messageCaptor.capture(), any(MessagePostProcessor.class));

Hope this helps !

0
1

You want to do this

    @ExtendWith(MockitoExtension.class)
    class TestClass {
        // Omitted code for brevity
        @InjectMocks private Service service;

        @Mock RabbitTemplate rabbitTemplate;

        @Captor ArgumentCaptor<MessagePostProcessor> messagePostProcessorArgumentCaptor;

        @Captor ArgumentCaptor<String> routingKeyCaptor;

        @Captor ArgumentCaptor<Object> messageCaptor;

        @Test
        void shouldConfirmDelayEquals5000() {
            // Arrange
            var myRequest = new MyRequest();
            final var delay = "5000";
            when(messageBrokerProps.getDelay()).thenReturn(delay);
            
            // Act
            service.sendToRetryQueue(myRequest);
        
            // Assert
            Mockito.verify(rabbitTemplate, times(1)).convertAndSend(
                routingKeyCaptor.capture(),
                messageCaptor.capture(),
                messagePostProcessorArgumentCaptor.capture()
            );

            var myRequestSent = (MyRequest) messageCaptor.getValue();
            assertThat(myRequestSent).isEqualTo(myRequest);

            var message = messagePostProcessorArgumentCaptor.getValue().postProcessMessage(new Message(myRequestSent.toString().getBytes()));
            assertEquals(delay, message.getMessageProperties().getHeader("x-delay"));
        }
    }

The sendToRetryQueue method that is in another class:

    public void sendtoRetryQueue(MyRequest myRequest) {
        rabbitTemplate.convertAndSend(
                messageBrokerProps.getRoutingKey(),
                myRequest,
                message -> {
                    message
                            .getMessageProperties()
                            .setHeader("x-delay", messageBrokerProps.getDelay());
                    return message;
                });
    }

Hope it helps.

0

I think it all depends on what you're really trying to test and what business value it adds.

  1. Do you want to test the RabbitTemplate itself? The Spring repo has tests for this, but IMHO you shouldn't need to do this.
  2. Are you testing a Spring Service and you have to verify that a message was sent?
  3. Do you want to make sure the message will reach its destination?

For (1) there are some examples of exactly the type of tests you're writing in the Spring Framework here in their unit tests for the RabbitTemplate.

For example, verifying that the underlying ConnectionFactory actually created a channel:

    txTemplate.execute(status -> {
        template.convertAndSend("foo", "bar");
        return null;
    });
    txTemplate.execute(status -> {
        template.convertAndSend("baz", "qux");
        return null;
    });
    verify(mockConnectionFactory, Mockito.times(1)).newConnection(any(ExecutorService.class), anyString());
    // ensure we used the same channel
    verify(mockConnection, times(1)).createChannel();

For (2) above, you don't need to use argument captors, etc. You can inject a mock RabbitTemplate into the service and I personally like to either test against the argument I called the method with or to use Mockito#any, etc.

FYI, in terms of assertions, I'd also take a look at AssertJ, it has a nice stamp of approval from Spring, and the fluent API for it (esp. with intellisense) makes it very easy to use.

For (3), I'd highly recommend https://www.testcontainers.org/ (if you're using docker), and I haven't checked it out but there may be a JUnit @Rule for creating a RabbitMQ broker (I'll have to check on this). I've done something like that for ActiveMQ Artemis which very quickly starts up a broker for you and you can consume the messages queued to it.

1
  • As these are just unit tests, I definitely don't want to use test containers. And no, I am not testing the RabbitTemplate, the spring developers have done that already. I want to test if the message is being sent with the expected arguments so any() is not an option.
    – Urosh T.
    Commented Sep 7, 2018 at 15:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.