60

I have Junit test that is testing jms message sending. I am using Spring jmsTemplate to to do this. Here I as in the following code I want to check whether the JMS template has called send message regardless what is it in the values of actuall parameters that are passed.

my publisher method the uses the jmsTemplate to send method looks like following inside..

jmsTemplate.send(jmsQueueProperties.getProperty(key), new MessageCreator()
{
    public Message createMessage(Session session) throws JMSException
    {
        ObjectMessage obj = session.createObjectMessage(dialogueServiceResponse);
        return obj;
}
});

in My tests..

JmsTemplate mockTemplate = Mockito.mock(JmsTemplate.class);
...
publisher.publishServiceMessage(response);
....
Mockito.verify(mockTemplate, 
    Mockito.times(1)).send("appointment.queue", 
        Mockito.any(MessageCreator.class));

But when in the execution i get

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers! ....

Cause is due to Mockito.any(MessageCreator.class) , but isn't there a way to test my send method is getting executed without creating an actual object in the MessageCreator.

Update And is there a way to check my session.createObjectMessage(dialogueServiceResponse) is getting called as well

Vikdor
  • 23,934
  • 10
  • 61
  • 84
kuhajeyan
  • 10,727
  • 10
  • 46
  • 71
  • mock and verify don't work well together. What you need is to create a spy object for the Class you wish to run these verifications on instead of just mocking it. – 3xil3 May 09 '13 at 10:14
  • 3
    @3xil3 - that's false. It's perfectly possible to verify calls to a Mocked object. – scubbo Oct 01 '18 at 20:16

7 Answers7

111

I think the rest of the message tells you what the problem is. When you use an argument matcher for one of the arguments, all the other arguments must also use an argument matcher:

Mockito.verify(mockTemplate, Mockito.times(1)).send(
    Mockito.eq("appointment.queue"), 
    Mockito.any(MessageCreator.class));
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Thanks. Yes. that helped to sort the issue. but what about if I want to check session.createObjectMessage(dialogueServiceResponse) getting called? – kuhajeyan May 09 '13 at 11:27
  • 2
    You would probably have to use a real JmsTemplate instance with a mocked Session to do that. Or you could externalize the message creation to another method, and unit test this method. – JB Nizet May 09 '13 at 11:43
5

For future readers. This will save you a lot of time.

We cannot use argument matcher and primitive/raw values together.

when(fooService.getResult("string",any(MyClass.class))).thenReturn(1); // will give error

when(fooService.getResult(anyString(),any(MyClass.class))).thenReturn(1); // correct
Adarsh D
  • 511
  • 6
  • 14
  • 1
    In my case, I have called the same metho two times changing the value which passes to that method to get two different results. in such scenario how to mock the same method for two times for different mock results – Sathya Molagoda Jun 01 '22 at 10:28
  • 1
    @SathyaMolagoda, use org.mockito.ArgumentMatchers.eq, as described here https://stackoverflow.com/a/50074126/8067983 – John Oct 04 '22 at 11:27
3

I think you cannot use argument matchers outside stubbing. I also got the same error but when I return, I had to do new string() instead of Mockito.anyString() and the error goes away. Example:

Mockito.when(mockedBean.mockedMethod(Mockito.anyString(), 
                                     Mockito.anyInt(),
                                     Mockito.anyInt(),
                                     Mockito.anyInt(),
                                     Mockito.anyBoolean())).thenReturn(new String()); 
vik_78
  • 1,107
  • 2
  • 13
  • 20
BruceWayne
  • 111
  • 1
  • 3
3

I can see that this question is about Java code, but I will share this because we use Mockito in Scala as well.

I had this exception thrown from the following code that mocks Play.api configurations

"Configurations Service" should {

    "return all dataset configurations" in {
      val configs = mock[Configuration]

      val testData = Seq("SOME VALUE")

      val loader = any[ConfigLoader[Seq[String]]]

      when(configs.get[Seq[String]](any[String])).thenReturn(testData) // EXCEPTIONN HERE ! 

      val configuration: ConfigurationsService = new ConfigurationsService(configs)

      assert(configuration.getSupportedDatasets() == testData)

    }
  }

In Scala methods can have Implicit parameters configs.get method has one explicit param and an Implicit one I passed a mock object and when an exception was thrown I was wondering what is going on as I didn't MIX params and mocks, it turned out that I had to pass mocks to implicit parameters as well, and this solved the problem.

 val loader = any[ConfigLoader[Seq[String]]] // configs.get has one implicit parameter that accepts ConfigLoader[Seq[String]] 

when(configs.get[Seq[String]](any[String])(loader)).thenReturn(testData)
Adelin
  • 18,144
  • 26
  • 115
  • 175
2

I was seeing this error about a mismatched # of arguments, despite having the correct number...

I realized this was because method being stubbed was static. When I converted it to non-static, it worked as expected.

fafrd
  • 1,017
  • 13
  • 17
0

Just wrap your String value with eq

Error

when(dictionaryService.getDictionaryValue(TYPES, IDENTIFIER, anyString()))
                .thenReturn("Double Awarding");
  • org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers!

Correct

when(dictionaryService.getDictionaryValue(eq(TYPES), eq(IDENTIFIER), anyString()))
                .thenReturn("Double Awarding");
razvang
  • 1,055
  • 11
  • 15
0

For this error, I found I needed to swap out an "any()" for an "anyBoolean()" where the method takes a primitive boolean type. In general it might be the case that you have to use a more specific method than "any()" when the method has primitive type parameters.

Adam Wise
  • 2,043
  • 20
  • 17