Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MockMVC how to test exception and response code in the same test case

I want to assert that an exception is raised and that the server returns an 500 internal server error.

To highlight the intent a code snippet is provided:

thrown.expect(NestedServletException.class);
this.mockMvc.perform(post("/account")
            .contentType(MediaType.APPLICATION_JSON)
            .content(requestString))
            .andExpect(status().isInternalServerError());

Of course it dosen't matter if I write isInternalServerError or isOk. The test will pass regardless if an exception is thrown below the throw.except statement.

How would you go about to solve this?


2 Answers

If you have an exception handler and you want to test for a specific exception, you could also assert that the instance is valid in the resolved exception.

.andExpect(result -> assertTrue(result.getResolvedException() instanceof WhateverException))

UPDATE (gavenkoa) Don't forget to inject @ExceptionHandler annotated methods to the test context or exception will occur at .perform() instead of capturing it with .andExpect(), basically register:

@ControllerAdvice
public class MyExceptionHandlers {
    @ExceptionHandler(BindException.class)
    public ResponseEntity<?> handle(BindException ex) { ... }
}

with @Import(value=...) or @ContextConfiguration(classes=...) or by other means.

like image 196
Oluwatobiloba Avatar answered Sep 02 '25 07:09

Oluwatobiloba


You can get a reference to the MvcResult and the possibly resolved exception and check with general JUnit assertions...

MvcResult result = this.mvc.perform(
        post("/api/some/endpoint")
                .contentType(TestUtil.APPLICATION_JSON_UTF8)
                .content(TestUtil.convertObjectToJsonBytes(someObject)))
        .andDo(print())
        .andExpect(status().is4xxClientError())
        .andReturn();

Optional<SomeException> someException = Optional.ofNullable((SomeException) result.getResolvedException());

someException.ifPresent( (se) -> assertThat(se, is(notNullValue())));
someException.ifPresent( (se) -> assertThat(se, is(instanceOf(SomeException.class))));
like image 33
Edward J Beckett Avatar answered Sep 02 '25 08:09

Edward J Beckett