有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法在Spring RestTemplate中模拟JSON响应

我试图在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) 个答案

  1. # 1 楼答案

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

    您要么必须模拟要在其中使用匹配器的对象(大多数情况下,您希望模拟最初倾向于使用匹配器参数的对象),要么输入一个固定值,而不是匹配器

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

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

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