gpt4 book ai didi

java - 使用 Mockito 测试 REST 删除方法

转载 作者:行者123 更新时间:2023-12-02 09:48:41 25 4
gpt4 key购买 nike

我需要帮助来使用 Mockito 的正确语法来测试 Spring Rest 模板删除方法。

服务代码:

@Override
public Boolean deleteCustomerItem(String customerNumber, String customerItemId)
throws Exception {
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("itemId", customerItemId);
try {
ResponseEntity<Void> deleteResponseEntity = restTemplate.exchange( deleteCustomerItemUrl, HttpMethod.DELETE, HttpEntity.EMPTY,
Void.class, uriVariables);
return deleteResponseEntity.getStatusCode().is2xxSuccessful();
} catch (Exception e) {
throw new AppCustomerException(e.getMessage());
}
}

单元测试代码:

@Test
public void testDeleteCustomerItem() throws AppCustomerException {
ResponseEntity<Void> noResponse = new ResponseEntity<Void>(HttpStatus.OK);
when(restTemplate.exchange(anyString(), any(HttpMethod.class), any(HttpEntity.class), Void.class, anyMap()))
.thenReturn(noResponse);
Boolean deleteStatus = appCustomerService.deleteCustomerItem("134", "7896");
assertEquals(Boolean.TRUE, deleteStatus);
}

异常(exception):

Mockito 匹配器的使用无效。 5 名匹配者预计 4 名已记录。

最佳答案

您应该将 Void.class 包装在 Mockito 匹配器中:

 when(restTemplate.exchange(
anyString(), any(HttpMethod.class), any(HttpEntity.class),
eq(Void.class), anyMap()))
.thenReturn(noResponse);

它的工作方式是所有输入都被 ArgumentMatcher 包装或不包装。

关于java - 使用 Mockito 测试 REST 删除方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56479013/

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