我正在尝试使用RestTemplate对API发送请求并从中检索一些资源来对以下Spring启动代码进行单元测试:
final URI targetUri = UriComponentsBuilder.fromUriString(baseUri)
.path("/myEntities").build().toUri();
final RequestEntity<Void> request = RequestEntity.get(targetUri).accept(HAL_JSON).build();
final Resources<MyEntity> resourceAccounts = restTemplate.exchange(request, new ResourcesType<MyEntity>() {
}).getBody();
在单元测试中,我使用Mockito嘲笑此请求 - 响应:
final Resources<MyEntity> myEntities = new Resources<>(myEntityList, links);
final ResponseEntity<Object> response = new ResponseEntity<Object>(myEntities, HttpStatus.OK);
when(restTemplate.exchange(any(RequestEntity.class), any(ResourcesType.class))).thenReturn(response);
它工作正常但我得到Unchecked invocation exchanged
因为我没有正确使用泛型。
我只是想知道这样做的正确和防弹方法是什么?我尝试将ResponseEntity
类型转换为MyEntity
,但这会导致编译异常(构造函数ResponseEntity<MyEntity> is undefined
)。