java - "Invalid use of argument matchers"但我只使用匹配器

标签 java testing junit mockito

我收到错误信息:

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"));

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

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

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()));

最佳答案

在评论中解决:

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

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


表示问题的两行是:

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

正如我在 a previous SO post 中所写,Mockito 匹配器主要通过副作用工作,因此 Matcher 方法和模拟对象方法之间的调用顺序对 Mockito 及其验证非常重要。对 configReader.getHBaseConfiguration() 的调用是在调用 any(JavaSparkContext.class) 之后调用模拟(在第一行中建立),它混淆 Mockito 认为您正在验证零参数方法 getHBaseConfigurationany 匹配的一个参数。这就是错误消息显示“预期有 0​​ 个匹配器,已记录 1 个”的原因:0 用于 getHBaseConfiguration,1 用于 any(JavaSparkContext.class)

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

关于java - "Invalid use of argument matchers"但我只使用匹配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35683829/

相关文章:

java - Java 中的可见性问题

java - 在 JTable 中编辑单元格时提供附加行为

java - 从自定义测试脚本/代码创建标准测试报告文件

javascript - AngularJS Controller : The Right Way

java - 无法接收嵌入的 ActiveMQ 统计消息

java - cvc-complex-type.2.4.c : The matching wildcard is strict, 但找不到元素 'property' 的声明

python - 在 Python 中对整个应用程序进行回归测试

javascript - 如何对 TweenMax 进行单元测试?潜在的模拟?

java - 如何测试 java.lang.Math 方法是否已被调用?

java - 单元测试时未找到自定义注释