在使用正确的Mockito语法测试Spring Rest Template删除方法时,我需要帮助。
服务代码:
@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);
}
例外:
无效地使用了Mockito Matchers。预计有5个符合条件的匹配器4个。
答案 0 :(得分:1)
when(restTemplate.exchange(
anyString(), any(HttpMethod.class), any(HttpEntity.class),
any(Void.class), anyMap()))
.thenReturn(noResponse);
您不应该组合蚂蚁匹配器,例如anyMap()和anyString() 在when()。thenReturn()语句中具有与eq(Void.class)类似的精确值
还可以用any()替换“ Void.class”
答案 1 :(得分:0)
您应将Void.class
包装在Mockito匹配器中:
when(restTemplate.exchange(
anyString(), any(HttpMethod.class), any(HttpEntity.class),
eq(Void.class), anyMap()))
.thenReturn(noResponse);
它的工作方式是所有输入都用ArgumentMatcher
包装或不包装。