当前位置: 首页 > 知识库问答 >
问题:

无法模拟Spring RestTemplate中的JSON响应

笪涛
2023-03-14

我试图模拟RestTemplate响应中的字符串,但代码中的错误如下。请提供投入。

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Misplaced argument matcher detected here:

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
   when(mock.get(anyInt())).thenReturn(null);
   doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
   verify(mock).someMethod(contains("foo"))

Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.

上述错误发生在这一行:

    when(this.userProfileClientRestTemplateProvider.currentUserProfileWithPermissionsRestTemplate()
               .exchange(
                any(RequestEntity.class),eq(String.class)))                .thenReturn(mockResponseEntityFromFile("com/cnanational/dealerplanadmin/service/applyRuleSetsToDealer/user-permissions.json", 
String.class, ResponseEntity.ok()));

共有1个答案

乐刚毅
2023-03-14

错误消息表明您在mock对象之外使用了一些mockito匹配器,如any(Object)anystring()

您要么模拟要在其中使用匹配器的对象(大多数情况下,您希望模拟首先使用匹配器参数的对象),要么放置固定值而不是匹配器。

出现此错误消息的另一种可能是尝试模拟final方法。

 类似资料:
  • 我在spring boot应用程序中用groovy(spock)编写了一个集成测试。其中一个应用程序bean称为,它具有以下方法: 在类中还有其他方法。在我的集成测试中,我只想模拟该特定方法的响应。以以下方式: 我希望进行其他验证,但不是这次。基本上,我想实现这一点,但与斯波克。我想取消执行方法

  • 我试图在测试中模拟一个调用,但我得到了一个错误,因为它调用了真正的方法,而不是模拟它。 这是我的方法 } 这是我的测试课 测试实际上调用了受保护的方法config Setter,并在设置代理时失败。帮助我理解我在这里做错了什么。

  • 我正在使用TestNG编写单元测试。问题是当我模拟System.CurrentTimeMillis时,它返回的是实际值,而不是模拟的值。理想情况下,它应该返回0L,但它返回的是实际值。我该怎么做才能继续?

  • 问题内容: 我正在尝试为向Web服务发出请求的程序包编写测试。我可能由于缺乏对TLS的了解而遇到问题。 目前,我的测试看起来像这样: 我的程序包具有一个要查询的Web服务基址的程序包变量(我希望它是一个常量。)。这是一个https URL。我在上面创建的测试服务器是纯HTTP,没有TLS。 默认情况下,我的测试失败,并显示错误“ tls:第一条记录看起来不像TLS握手”。 为了使它起作用,我的测试

  • 我不明白为什么不能将模拟的预定义行为移到and:块中。

  • 是否可以使用线雾模拟Jmeter中API的json响应。如果是,请您分享一步一步的过程。