gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:46:28 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0