说
我有一个方法getTemplateData(),我想在其中模拟一个restTemplate.exchange()方法调用
public List<String> getTemplateData(String templateId, String storeId, String projectId) {
RestTemplate restTemplate = new RestTemplate();
Map<String, String> bodyObject = new HashMap<>();
bodyObject.put("functionalAreaId", templateId);
bodyObject.put("storeId", storeId);
bodyObject.put("projectId", projectId);
HttpEntity<?> requestEntity = new HttpEntity<>(bodyObject, null);
ResponseEntity<List<String>> result =
restTemplate.exchange(
BaseUrl + "/template",
HttpMethod.POST,
requestEntity,
new ParameterizedTypeReference<List<String>>() {});
List<String> screens = result.getBody().stream().collect(Collectors.toList());
log.info(
"Completed executing the method getTemplateData for the templateId:{} and storeId:{}",
templateId,
storeId);
return screens;
}
我想模仿那条线
ResponseEntity<List<String>> result =
restTemplate.exchange(
BaseUrl + "/template",
HttpMethod.POST,
requestEntity,
new ParameterizedTypeReference<List<String>>() {});
是否可以在Java中模拟语句?
答案 0 :(得分:0)
是的,可以嘲笑。
@Test
public void test() {
// let's create mock first, you can use annotation also
RestTemplate mockTemplate = Mockito.mock(RestTemplate.class);
Mockito.when(mockTemplate.exchange(Mockito.eq(BaseUrl + "/template"),
Mockito.eq(HttpMethod.POST),
Mockito.eq(requestEntity),
Mockito.any(ParameterizedTypeReference.class))
.thenReturn(new ResponseEntity<>(Arrays.asList("data"), HttpStatus.OK))
}