“无效使用参数匹配器”,但我仅使用匹配器

Kon*_*kov 4 java testing junit mockito

我收到错误消息:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException:参数匹配器的无效使用!预期0个匹配器,记录1个:-> * .SegmentExportingTest.happyDay(SegmentExportingTest.java:37)如果匹配器与原始值组合,则可能发生此异常://不正确:someMethod(anyObject(),“原始字符串”); 使用匹配器时,所有参数都必须由匹配器提供。例如://正确:someMethod(anyObject(),eq(“字符串由匹配器”));

但实际上,我仅在方法的参数中使用匹配器。

下一个代码是上述错误的来源。

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()));
Run Code Online (Sandbox Code Playgroud)

Jef*_*ica 5

在评论中解决:

我在单独的行中提取了configReader.getHBaseConfiguration(),问题被隐藏了。

您的特定问题是在设置匹配器的过程中正在调用模拟方法


指示问题的两行是:

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

正如我在之前的SO帖子中所写,Mockito匹配器主要通过副作用起作用,因此Matcher方法和模拟对象方法之间的调用顺序对Mockito及其验证非常重要。对的调用configReader.getHBaseConfiguration()是在对调用之后发生的对模拟(在第一行中建立的)的调用any(JavaSparkContext.class),这使Mockito认为您正在getHBaseConfiguration使用一个any匹配的参数来验证零参数方法。这就是为什么错误消息显示“预期有0个匹配器,已记录1个”的原因:0代表getHBaseConfiguration,1代表any(JavaSparkContext.class)

为了安全起见,在使用Mockito匹配器时,请确保传递给匹配器的所有值都是预先计算的:它们都应该是常量文字,简单的数学表达式或变量。在存根/验证开始之前,任何涉及方法调用的内容都应提取到局部变量中。