shi*_*uno 6 java rest spring resttemplate
在测试中,我希望命中一个返回类型列表的端点。目前我有
@Test
public void when_endpoint_is_hit_then_return_list(){
//Given
ParameterizedTypeReference<List<Example>> responseType = new ParameterizedTypeReference<List<Example>>() {};
String targetUrl = "/path/to/hit/" + expectedExample.getParameterOfList();
//When
//This works however highlights an unchecked assignment of List to List<Example>
List<Example> actualExample = restTemplate.getForObject(targetUrl, List.class);
//This does not work
List<Example> actualExample = restTemplate.getForObject(targetUrl, responseType);
//This does not work either
List<Example> actualExample = restTemplate.exchange(targetUrl, HttpMethod.GET, null, new ParameterizedTypeReference<List<Example>>() {});
//Then
//Assert Results
}
Run Code Online (Sandbox Code Playgroud)
getForObject 方法的问题是 ParameterizedTypeReference 使 getForObject 方法无法解析,因为类型不匹配。
交换方法的问题是类型不兼容。必需的列表,但“交换”被推断为 ResponseEntity:不存在类型变量的实例,因此 ResponseEntity 符合列表
在这种情况下,如何正确使用 ParameterizedTypeReference 来安全地返回我想要的 List 类型?
Jav*_*adi 13
从文档:
对给定的 URI 模板执行 HTTP 方法,将给定的请求实体写入请求,并将响应作为 ResponseEntity 返回。给定的 ParameterizedTypeReference 用于传递泛型类型信息:
Run Code Online (Sandbox Code Playgroud)ParameterizedTypeReference<List<MyBean>> myBean = new ParameterizedTypeReference<List<MyBean>>() {}; ResponseEntity<List<MyBean>> response = template.exchange("http://example.com",HttpMethod.GET, null, myBean);
因此,在您的情况下,您可以:
ResponseEntity<List<Example>> actualExample = restTemplate.exchange(targetUrl, HttpMethod.GET, null, new ParameterizedTypeReference<List<Example>>() {});
List<Example> exampleList = actualExample.getBody();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14690 次 |
| 最近记录: |