Description
I'm trying to test my Controller using MockMvc.
The service used by Controller throws RuntimeException if something is wrong.
The spring-boot's default exception resolver catches this exception and responds with status 500.
But when I use MockMvc in my test, the test method just throws the exception instead of catch status 500.
If I add explicit exception resolver using @ExceptionHandler
, then test method starts to work.
The simple example. My Controller just throws new RuntimeException()
for simplicity.
@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
public class ControllerTests {
@Autowired
private MockMvc mvc;
@Test
public void testInternalServerError() throws Exception {
mvc.perform(get("/api/data"))
.andExpect(status().isInternalServerError());
}
}
Expected result:
Test catches status 500 and passes.
Actual result:
The exception is thrown and test fails.
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.RuntimeException
Maybe I'm wrong assuming that spring-boot installs some default mvc exception handler. But anyway the real application returns status 500 with properly formatted JSON of error details. So I think the MockMvc should do the same.
I can add the reproducible example if someone confirms that this is really not intended behaviour.