【问题标题】:org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers! 2 matchers expected, 3 recordedorg.mockito.exceptions.misusing.InvalidUseOfMatchersException:参数匹配器的使用无效!预计 2 个匹配器,记录 3 个
【发布时间】:2020-09-17 18:55:51
【问题描述】:

我知道在这个平台上被多次询问过。我还检查了提供的解决方案,即使用所有原始参数或所有 Matcher 参数。就我而言,Argument Matcher(any, anyString) 已用于所有参数,但仍然出现错误。

代码:

Mockito.when(service.createReq(Mockito.any(RequestDto.class))).thenReturn(Mockito.any(TermReq.class));
Mockito.when(utils.sendPOSTRequest(Mockito.anyString(),Mockito.anyString())).thenReturn(Mockito.anyString());

上面一行的错误是:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
2 matchers expected, 3 recorded:

谁能指出可能是什么问题。

谢谢,

【问题讨论】:

    标签: spring-boot unit-testing mockito junit-jupiter


    【解决方案1】:

    您不能从像 thenReturn(Mockito.any(TermReq.class)) 这样的模拟方法返回参数匹配器。这是一个无效的用途。

    您应该返回一个实际值或参数捕获器。

    【讨论】:

      【解决方案2】:

      如果你想模拟一个方法的返回值,你应该决定在 when 子句之后返回什么对象。您不能返回新的参数匹配器。我建议在您的测试场景中返回新的模拟对象,如下所示:

      TermReq termReq = Mockito.mock(TermReq.class);  // create mock
      Mockito.when(termReq.getId()).thenReturn(1L) // mock required get methods
      Mockito.when(service.createReq(Mockito.any(RequestDto.class))).thenReturn(termReq); // then return in case of the service method call
      

      通过这种使用方式,您可以处理结果或将结果与模拟对象进行比较。

      【讨论】:

        猜你喜欢
        • 2020-03-23
        • 1970-01-01
        • 2021-09-24
        • 1970-01-01
        • 2022-07-20
        • 2014-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多