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?
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.
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))));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With