java - Mockito 匹配器 : matching a Class type in parameter list

标签 java generics mockito matcher

我正在使用 Eclipse 处理 Java、Spring 的 RestTemplate 和 Mockito。我正在尝试模拟 Spring 的 rest 模板,我模拟的方法的最后一个参数是类类型。下面是函数的签名:

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

我最初尝试模拟这个方法如下:

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

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

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

Eclipse 然后建议我使用“类”类型转换最后一个参数,但如果我将它转换为“类”或其他类型,似乎不起作用。

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

到目前为止,我看到的答案主要与通用集合有关。此处的任何帮助将不胜感激。

最佳答案

想通了。

被调用的方法是参数化方法,但无法从匹配器参数推断参数类型(最后一个参数是类类型)。

进行显式调用

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

解决了我的问题。

关于java - Mockito 匹配器 : matching a Class type in parameter list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32574375/

相关文章:

java.util.regex.PatternSyntaxException : Illegal repetition near index 12

java - 为什么PowerMock会尝试加载一些在非模拟类方法中使用的类?

java - 玩!框架支付处理(电子商务/ Paypal )

java - 旋转玩家面对行星

java - 具有相同签名的两种方法,为什么有效

c# - 如何使用子泛型接口(interface)实现泛型接口(interface)

java - 在子类上使用 Mockito spy 时调用抽象类中的可变长度参数方法抛出异常

java - 使用 Mockito 模拟 lombok @Getter 字段

java - 如何使用 lambda 获取 HashMap 中值的键数

c# - 指定类本身的泛型类的基类约束