2

I need to verify a call for handler.sendMessage(msg).

Code:

//This bundleImportStorage will send message to UI handler by passing message object
bundleImporter.bundleImportFromStorage(intent);

//In this line I am getting error
when(uiHandler.sendMessage(any(Message.class))).thenReturn(true);

Exception details:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
  Invalid use of argument matchers!
  2 matchers expected, 1 recorded:
  -> at com.fio.installmanager.nonui.com.bundleimport.TestBundleImport.testIntentExtras(TestBundleImport.java:69)

  This exception may occur if matchers are combined with raw values:
      //incorrect:
      someMethod(anyObject(), "raw String");
  When using matchers, all arguments have to be provided by matchers.
  For example:
      //correct:
      someMethod(anyObject(), eq("String by matcher"));
peterh
  • 11,875
  • 18
  • 85
  • 108
AnkiReddy L
  • 33
  • 1
  • 3

1 Answers1

5

Based on the message "2 matchers expected, 1 recorded", this can happens if UiHandler.sendMessage(Message) is a final method that delegates to a non-final two-argument method (often an overload of the same name). This is a problem because Mockito insists on each argument having exactly one matcher, if any matchers are used at all. Because final methods are invoked by static dispatch, and because Mockito works by dynamically overriding the mocked class, Mockito's first interaction is with a two-argument method that it assumes you're stubbing with a single matcher (explaining the otherwise-confusing error message).

If feasible, ensure that UiHandler and sendMessage are both public and non-final. If not, you may need to resort to Robolectric or PowerMock to overwrite the final method at the bytecode level.

I've written more about Mockito internals, including the need for one matcher per argument, here on SO: How do Mockito matchers work?

Community
  • 1
  • 1
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251