4

I get the error message:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers! 0 matchers expected, 1 recorded: -> at *.SegmentExportingTest.happyDay(SegmentExportingTest.java:37) 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"));

but in reality I use only matchers in arguments of the method.

The next code is a source of the error above.

ConfigReader configReader = mock(ConfigReader.class);
    when(configReader.getSparkConfig())
            .thenReturn(new SparkConf().setMaster("local[2]").setAppName("app"));
    when(configReader.getHBaseConfiguration()).thenReturn(new Configuration());

    SparkProfilesReader sparkProfilesReader = mock(SparkProfilesReader.class);
    ProfileSegmentExporter profileSegmentExporter = mock(ProfileSegmentExporter.class);

    //--
    new SegmentExporting().process(configReader, sparkProfilesReader, profileSegmentExporter);
    //--

    InOrder inOrder = inOrder(sparkProfilesReader, profileSegmentExporter);
    inOrder.verify(sparkProfilesReader).readProfiles(any(JavaSparkContext.class),
            refEq(configReader.getHBaseConfiguration()));
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183

1 Answers1

6

Resolved in the comments:

I extracted configReader.getHBaseConfiguration() in the separate line and the issue was hided.

Your specific problem is that you're calling a mock method in the middle of setting up your matchers.


The two lines that indicate the problem are these:

when(configReader.getHBaseConfiguration()).thenReturn(new Configuration());
// ...
inOrder.verify(sparkProfilesReader).readProfiles(any(JavaSparkContext.class),
    refEq(configReader.getHBaseConfiguration()));

As I wrote in a previous SO post, Mockito matchers work mostly via side-effects, so call order among Matcher methods and mock-object methods matters a lot to Mockito and its validation. The call to configReader.getHBaseConfiguration() is a call to a mock (as established in the first line) that happens after your call to any(JavaSparkContext.class), which confuses Mockito into thinking you're verifying zero-arg method getHBaseConfiguration with one argument that any matches. That's why the error message says "0 matchers expected, 1 recorded": The 0 is for getHBaseConfiguration and the 1 is any(JavaSparkContext.class).

To be safe, when using Mockito matchers, make sure the values passed to the matchers are all pre-calculated: They should all be constant literals, simple math expressions, or variables. Anything that involves a method call should be extracted to a local variable before stubbing/verifying begins.

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