dar*_*bre 6 java unit-testing compiler-errors matcher mockito
我应该如何编写以下Mockito Matchers以使呼叫不模糊?
我试图在我的代码中模拟的实际函数调用是:
//Variables
String url = http://theServer:8080/oath2-v1/token;
HttpEntity<String> request = new HttpEntity<String>("name=value",headers);
//Method call I am trying to mock using Mockito
response=cmsRestTemplate.exchange(url, HttpMethod.POST, request, DdsOAuthToken.class);
Run Code Online (Sandbox Code Playgroud)
以下是我的单元测试案例的片段.它包含以下模拟调用以模拟上述调用,但不幸的是编译器发现它不明确并且不会编译.
//From the Unit Test...
when(restTemplate.exchange(
Matchers.anyString(),
Matchers.any(HttpMethod.class),
Matchers.any(HttpEntity.class),
Matchers.<Class<DdsOAuthToken>>any(),
Matchers.anyVararg()).thenReturn(response));
Run Code Online (Sandbox Code Playgroud)
我得到的错误如下:
The method exchange(String, HttpMethod, HttpEntity<?>, Class<DdsOAuthToken>, Object[]) is ambiguous for the type RestTemplate
Run Code Online (Sandbox Code Playgroud)
这是一个Spring RestTemplate api调用.特别是2个api调用它发现含糊不清的是以下2个调用:
1. exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables)
2. exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType, Object... uriVariables)
Run Code Online (Sandbox Code Playgroud)
我试图模仿上面的#1.但Java编译器无法判断我是否正在尝试调用#1或#2.究竟应该如何编写Mockito匹配器,以便它知道我想要#1而不是#2?
通常,模拟您无法控制的类是一个错误的决定。Spring 框架附带了实用程序类,可以帮助您测试框架的使用情况。
例如,MockRestServiceServer是一个虚拟服务器,它将提供有效的响应RestTemplate,因此您不需要模拟它。
RestTemplate restTemplate = new RestTemplate();
MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
mockServer.expect(requestTo("/greeting"))
.andRespond(withSuccess("Hello world", "text/plain"));
// use RestTemplate ...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2750 次 |
| 最近记录: |