mercredi 1 août 2018

How to test the content of a result when testing ExceptionHandler in Spring?

Trying to test my RestControllerAdviser that is using the @ControllerAdvice annotation and has a few ExceptionHandlers in there such as..

@ExceptionHandler(value = InvocationTargetException.class)
public ResponseEntity<Object> handleInvocationTargetException(InvocationTargetException e) {
    String errorMessage = "Error Caught: Internal Server Error - Invocation Target Exception.";
    log.error(errorMessage, e);
    return response(errorMessage, HttpStatus.INTERNAL_SERVER_ERROR);
}


...

/**
 * No handler found, for things such as 404 errors.
 * 
 * @param e
 * @return
 */
@Override
protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException e, HttpHeaders headers,
        HttpStatus status, WebRequest request) {
    String errorMessage = "Error Caught: " + e.getMessage();
    log.error(errorMessage, e);
    return response(errorMessage, status);
}

So far trying to setup my tests I went through some other StackOverflow questions to use MockMvc and get a MvcResult object back. I can check the status fine...but the content of the result is not what I expect it's empty.

So for example my test file is...

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { RestControllerAdviserTestConfig.class })
public class RestControllerAdviserTest {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Mock
    private RestControllerAdviser statusController;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test(expected = NoHandlerFoundException.class)
    public void noHandlerFoundExceptionTest() throws Exception {
        MvcResult result = mockMvc.perform(get("/invalidurl")).andExpect(status().isNotFound()).andReturn();
    }
}

And the last test the result object, when looking in the debugger has no content in it...when I would expect it to have something like "Error Caught: .." based on my ExceptionHandler.

How can I test the content of the response to my exception handler?

Aucun commentaire:

Enregistrer un commentaire