Mockito Matchers:匹配参数列表中的Class类型

pip*_*970 8 java generics matcher mockito

我正在使用Java,Spring的RestTemplate和Mockito,使用Eclipse.我试图模拟Spring的rest模板,我模拟的方法的最后一个参数是Class类型.以下是该功能的签名:

public <T> ResponseEntity<T> exchange(URI url,
                                  HttpMethod method,
                                  HttpEntity<?> requestEntity,
                                  Class<T> responseType)
                       throws RestClientException
Run Code Online (Sandbox Code Playgroud)

我嘲笑这个方法的初步尝试如下:

//given restTemplate returns exception
when(restTemplate.exchange(isA(URI.class), eq(HttpMethod.POST), isA(HttpEntity.class), eq(Long.class))).thenThrow(new RestClientException(EXCEPTION_MESSAGE));
Run Code Online (Sandbox Code Playgroud)

但是,这行代码会从eclipse中产生以下错误:

The method exchange(URI, HttpMethod, HttpEntity<?>, Class<T>) in the type RestTemplate is not applicable for the arguments (URI, HttpMethod, HttpEntity, Class<Long>)
Run Code Online (Sandbox Code Playgroud)

Eclipse然后建议我使用'Class'强制转换投射最后一个参数,但是如果我将它转换为'Class'或其他类型,它似乎不起作用.

我一直在网上寻求帮助,但似乎对请求的参数是类类型的事实感到困惑.

到目前为止我看过的答案主要与通用集合有关.这里的任何帮助将不胜感激.

pip*_*970 8

想通了.

被调用的方法是参数化方法,但无法从matcher参数推断出参数类型(最后一个参数是Class类型).

进行显式调用

when(restTemplate.<Long>exchange(isA(URI.class),eq(HttpMethod.POST),isA(HttpEntity.class), eq(Long.class))).thenThrow(new RestClientException(EXCEPTION_MESSAGE));
Run Code Online (Sandbox Code Playgroud)

解决了我的问题.


ksw*_*ghs 0

下面的代码片段对我有用。对于请求实体,我使用any()而不是isA()。

PowerMockito
    .when(restTemplate.exchange(
            Matchers.isA(URI.class),
            Matchers.eq(HttpMethod.POST),
            Matchers.<HttpEntity<?>> any(),
            Matchers.eq(Long.class)))
    .thenThrow(new RestClientException(EXCEPTION_MESSAGE));
Run Code Online (Sandbox Code Playgroud)