java Mockito 匹配器:匹配参数列表中的类类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32574375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mockito Matchers: matching a Class type in parameter list
提问by piper1970
I am working with Java, Spring's RestTemplate, and Mockito, using Eclipse. I am trying to mock Spring's rest template, and the last parameter for the method I am mocking is a Class type. Below is the signature for the function:
我正在使用 Eclipse 使用 Java、Spring 的 RestTemplate 和 Mockito。我正在尝试模拟 Spring 的 rest 模板,我模拟的方法的最后一个参数是 Class 类型。下面是函数的签名:
public <T> ResponseEntity<T> exchange(URI url,
HttpMethod method,
HttpEntity<?> requestEntity,
Class<T> responseType)
throws RestClientException
The initial attempt I made to mock this method is as follows:
我为模拟此方法所做的初步尝试如下:
//given restTemplate returns exception
when(restTemplate.exchange(isA(URI.class), eq(HttpMethod.POST), isA(HttpEntity.class), eq(Long.class))).thenThrow(new RestClientException(EXCEPTION_MESSAGE));
However, this line of code produces the following error from eclipse:
但是,这行代码在 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 then suggests I cast the last parameter with a 'Class' cast, but does not seem to work if I cast it to a 'Class', or other type.
Eclipse 然后建议我将最后一个参数强制转换为“Class”,但如果我将它强制转换为“Class”或其他类型,则它似乎不起作用。
I've been looking online for help on this, but seem to stumped on the fact that the parameter requested is a class type.
我一直在网上寻求这方面的帮助,但似乎对请求的参数是类类型这一事实感到困惑。
The answers I've looked at so far have been mainly related to generic collections. Any help here would be greatly appreciated.
到目前为止,我看到的答案主要与泛型集合有关。这里的任何帮助将不胜感激。
回答by piper1970
Figured out.
想通了。
The method being called was a parameterized method, but could not infer the parameter type from the matcher argument (the last argument was of type Class).
被调用的方法是参数化方法,但无法从匹配器参数(最后一个参数是 Class 类型)推断参数类型。
Making the explicit call
进行显式调用
when(restTemplate.<Long>exchange(isA(URI.class),eq(HttpMethod.POST),isA(HttpEntity.class), eq(Long.class))).thenThrow(new RestClientException(EXCEPTION_MESSAGE));
fixed my problem.
解决了我的问题。
回答by kswaughs
Below code snippet worked for me. For request entity, I used any() instead of isA().
下面的代码片段对我有用。对于请求实体,我使用 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));