Java &引用;参数匹配器的使用无效“;但我只使用匹配器

Java &引用;参数匹配器的使用无效“;但我只使用匹配器,java,testing,junit,mockito,Java,Testing,Junit,Mockito,我收到错误消息: org.mockito.exceptions.misusing.invalidUseofMatchers异常: 参数匹配器的使用无效! 应为0个匹配器,记录了1个: ->在*.SegmentExportingTest.happyDay(SegmentExportingTest.java:37) 如果匹配器与原始值组合,则可能发生此异常: //不正确: someMethod(anyObject(),“原始字符串”); 使用匹配器时,所有参数都必须由匹配器提供。 例如: //正确:

我收到错误消息:

org.mockito.exceptions.misusing.invalidUseofMatchers异常: 参数匹配器的使用无效! 应为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()));

在评论中解决:

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

你的具体问题是,在设置匹配器的过程中,你在调用模拟方法。


指示问题的两行是:

when(configReader.getHBaseConfiguration()).thenReturn(new Configuration());
// ...
inOrder.verify(sparkProfilesReader).readProfiles(any(JavaSparkContext.class),
    refEq(configReader.getHBaseConfiguration()));
正如我在中所写的,Mockito匹配器主要通过副作用工作,因此匹配器方法和mock对象方法之间的调用顺序对Mockito及其验证非常重要。调用
configReader.getHBaseConfiguration()
是对模拟的调用(如第一行中所建立的),该调用发生在调用
any(JavaSparkContext.class)
之后,这会使Mockito误以为您正在验证零参数方法
getHBaseConfiguration
,其中一个参数与
any
匹配。这就是为什么错误消息显示“预期0个匹配器,记录1个”:0表示
getHBaseConfiguration
,1表示
any(JavaSparkContext.class)


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

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