ResponseEntity<List<AgreementRecord>> myEntity = new
ResponseEntity<List<AgreementRecord>>(HttpStatus.ACCEPTED);
when(restTemplate.exchange(
ArgumentMatchers.anyString(),
ArgumentMatchers.any(HttpMethod.class),
ArgumentMatchers.<HttpEntity<?>>any(),
ArgumentMatchers.<Class<?>>any())).thenReturn(myEntity);
其余模板从应用程序返回一个列表 Eclipse 抛出编译错误
OngoingStubbing 类型中的 thenReturn(ResponseEntity) 方法> 不适用于参数 (响应实体>)
休息模板
ResponseEntity<List<AgreementRecord>> responseEntity =
restTemplate.exchange(smoUrl+ GET_AGREEMENT_RECORDS + customerId
,HttpMethod.GET,null,new
ParameterizedTypeReference<List<AgreementRecord>>() {
});
responseEntity.getBody();
最佳答案
你可以做的一件事是使用 doReturn() 回避 Mockito 的编译时类型检查。 .
doReturn(myEntity)
.when(restTemplate)
.exchange(
ArgumentMatchers.anyString(),
ArgumentMatchers.any(HttpMethod.class)
ArgumentMatchers.<HttpEntity<?>>any(),
ArgumentMatchers.<Class<?>>any()));
这将返回 myEntity,而不进行编译时类型检查。如果您的类型错误,您一运行测试就会发现。
编辑:
@Test()
public void test() {
class AgreementRecord {}
ResponseEntity<List<AgreementRecord>> myEntity = new ResponseEntity<>(
Arrays.asList(new AgreementRecord()), HttpStatus.ACCEPTED);
doReturn(myEntity)
.when(restTemplate)
.exchange(
anyString(),
any(HttpMethod.class),
any(),
any(ParameterizedTypeReference.class));
ResponseEntity<List<AgreementRecord>> responseEntity = restTemplate.exchange(
"url", HttpMethod.GET, null, new ParameterizedTypeReference<List<AgreementRecord>>() {});
List<AgreementRecord> body = responseEntity.getBody();
assertTrue(responseEntity.getStatusCode().is2xxSuccessful());
assertNotNull(body);
}
关于java - 模拟休息模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51263696/