【问题标题】:Unable to mock a JSON response in Spring RestTemplate无法在 Spring RestTemplate 中模拟 JSON 响应
【发布时间】:2019-06-13 03:55:43
【问题描述】:

我正在尝试在 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()));

【问题讨论】:

  • 分享完整的课程和日志。 this.userProfileClientRestTemplateProvider.currentUserProfileWithPermissionsRestTemplate() 这是模拟对象吗?

标签: java spring junit mockito resttemplate


【解决方案1】:

错误消息表明您在模拟对象之外使用了一些模拟匹配器,例如 any(Object) 或 anyString()。

您要么必须模拟要在其中使用匹配器的对象(大多数情况下,您要模拟首先倾向于使用匹配器参数的对象),或者放置一个固定值而不是匹配器。

如果您尝试模拟 final 方法,则会出现此错误消息的另一种可能性。

如需更详细的答案,我们需要查看您的代码。

如果我们可以帮助您或提供更多信息来帮助我们解决您的问题,请告诉我们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    相关资源
    最近更新 更多