gpt4 book ai didi

java - 是否可以在 Java 中使用 Mockito 来模拟语句?

转载 作者:行者123 更新时间:2023-12-01 16:46:18 25 4
gpt4 key购买 nike

说,

我有一个方法 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 中模拟语句?

最佳答案

是的,这可以被 mock 。

@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))
}

关于java - 是否可以在 Java 中使用 Mockito 来模拟语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61769940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com