Controller

@RequestMapping( value = "api/message/{id}", method = RequestMethod.DELETE) public ResponseEntity<?> deleteMessage(@PathVariable Long id) { messageService.delete(id); return new ResponseEntity<>(HttpStatus.OK); } 

You need to check for an exception if you request the removal of a non-existing id.

Returns

 { "timestamp": 1483566196066, "status": 500, "error": "Internal Server Error", "exception": "org.springframework.dao.EmptyResultDataAccessException", "message": "No class com.sttech.springrest.model.Message entity with id 1000 exists!", "path": "/api/message/1000" } 

Test method

 @Test(expected = EmptyResultDataAccessException.class) public void deleteMessageIfNotFoundThenException() { messageController.deleteMessage(2L); } 

Returns an error

java.lang.AssertionError: Expected exception: org.springframework.dao.EmptyResultDataAccessException

If so:

 @Test(expected = EmptyResultDataAccessException.class) public void deleteMessageIfNotFoundThenException1() { when(messageController.deleteMessage(2L)); then(caughtException()) .isInstanceOf(EmptyResultDataAccessException.class) .hasMessageContaining("entity with id 2 exists!"); } 

Returns an error

 java.lang.Exception: Unexpected exception, expected<org.springframework.dao.EmptyResultDataAccessException> but was<java.lang.AssertionError> 

In general, this exception should be tested in the controller?

    1 answer 1

    It is necessary to test only if there is a behavior. In your case, you can check that the controller called the correct method from the service / repository and returned the correct result. I would not test the exception, but if you want, you can

     @Test(expected = EmptyResultDataAccessException.class) public void deleteMessageIfNotFoundThenException1() { when(messageService.delete(2L)).thenThrow(new EmptyResultDataAccessException()); messageController.deleteMessage(2L); } 

    If you are doing a REST service, the DELETE operation should be idempotent, i.e. the state of the system does not change, even if the method has been called several times (N> 0) in a row.