我需要幫助使用 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); }例外:Mockito Matchers 的使用無效。5 匹配預期 4 記錄。
2 回答

開滿天機
TA貢獻1786條經驗 獲得超13個贊
您應該將其包裝Void.class
在 Mockito 匹配器中:
when(restTemplate.exchange( anyString(), any(HttpMethod.class), any(HttpEntity.class), eq(Void.class), anyMap())) .thenReturn(noResponse);
它的工作方式是所有輸入都被ArgumentMatcher
包裝或沒有。

慕田峪7331174
TA貢獻1828條經驗 獲得超13個贊
when(restTemplate.exchange( anyString(), any(HttpMethod.class), any(HttpEntity.class), any(Void.class), anyMap())) .thenReturn(noResponse);
您不應該在 when().thenReturn() 語句中將 anyMap() 和 anyString() 等螞蟻匹配器與精確值(例如 eq(Void.class))結合起來
你也可以用 any() 替換“Void.class”
添加回答
舉報
0/150
提交
取消