无法在Spring RestTemplate中模拟JSON响应

时间:2019-06-13 03:55:43

标签: java spring junit mockito resttemplate

我正在尝试在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 个答案:

答案 0 :(得分:0)

该错误消息表明您在模拟对象外部使用了诸如any(Object)anyString()之类的模拟匹配器。

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

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

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

请告知我们是否可以帮助您或提供更多信息来帮助我们解决您的问题。