簡體   English   中英

使用Mockito測試REST刪除方法

[英]Test REST Delete Method using Mockito

我需要使用正確的Mockito語法來測試Spring Rest Template Delete方法的幫助。

服務代碼:

@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個符合條件的匹配器。

 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”

您應該將Void.class包裝在Mockito匹配器中:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM