vendredi 10 juillet 2020

Testing Controller Advice Exception Handler

How can i test a ControllerAdvice using Mockito/MVC? I made successful when calling HTTP requests! However, when i build the test (code below), it doesnt work:

@ControllerAdvice

public class HandlerGenericHttpRequest {

private final String messageResourceNotFound = "URL not found for current request";

@ExceptionHandler({HandlerExceptionNotFound.class})
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public @ResponseBody HandlerGenericHttpResponse handleResourceNotFound(final HandlerExceptionNotFound exception,
                                                                       final HttpServletRequest request) {
    return exceptionResponseHandler(request.getRequestURI(),
                                    exception.getMessage());
}

@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public @ResponseBody HandlerGenericHttpResponse handleNoHandlerFound(final NoHandlerFoundException exception,
                                                                     final HttpServletRequest request) {
    return exceptionResponseHandler(request.getRequestURI(),
                                    messageResourceNotFound);
}

// ommited for brevied

Now, my test doesnt working:

@Before
public void init() {
    mockMvc = MockMvcBuilders.standaloneSetup(getAddressEntryPoint)
                             .setControllerAdvice(new HandlerGenericHttpRequest())
                             .build();
}

@Test
public void handleResourceNotFound__Error__404() throws Exception  {
    MockHttpServletResponse response = mockMvc.perform(
            get("/address-invalid/zipcode/".concat(zipCodeInvalid))
                    .accept(MediaType.APPLICATION_JSON)) 
            .andReturn().getResponse();
    assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
    assertThat(response.getContentAsString()).isEmpty();

}

The test pass successful, but doesnt coverage any @ExceptionHandler.

Aucun commentaire:

Enregistrer un commentaire