Suresh
Suresh

Reputation: 515

Test REST Delete Method using Mockito

I need help in using the right syntax for Mockito to test the Spring Rest Template Delete Method.

Service Code:

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

Unit Test Code:

@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:

Invalid use of Mockito Matchers. 5 matchers expected 4 recorded.

Upvotes: 1

Views: 1456

Answers (2)

ghazouan badr
ghazouan badr

Reputation: 486

 when(restTemplate.exchange(
      anyString(), any(HttpMethod.class), any(HttpEntity.class), 
      any(Void.class), anyMap()))
 .thenReturn(noResponse);
  • you should not combine ant matchers such anyMap() and anyString() with exact values like eq(Void.class) in when().thenReturn() statement

  • also you can replace "Void.class" with any()

Upvotes: 1

Maciej Kowalski
Maciej Kowalski

Reputation: 26522

You should wrap the Void.class within a Mockito matcher:

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

The way it works is that all the inputs are ArgumentMatcher wrapped or none.

Upvotes: 1

Related Questions