how to treat controller exception with mockmvc

Easier way is to inject @ExceptionHandler into your Spring Test Context or it throws exception right in MockMvc.perform() just before .andExpect().

@ContextConfiguration(classes = { My_ExceptionHandler_AreHere.class })
@AutoConfigureMockMvc
public class Test {
    @Autowired
    private MockMvc mvc;

    @Test
    public void test() {
        RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/update")
                .param("branchId", "13000")
                .param("triggerId", "1");
        MvcResult mvcResult = mvc.perform(requestBuilder)
                .andExpect(MockMvcResultMatchers.status().is4xxClientError())
                .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(__ -> Assert.assertThat(
                        __.getResolvedException(),
                        CoreMatchers.instanceOf(SecurityException.class)))
                .andReturn();
}

That way MvcResult.getResolvedException() holds @Controller's exception!

  • https://stackoverflow.com/a/62910352/173149
  • https://stackoverflow.com/a/61016827/173149
  • Testing Spring MVC @ExceptionHandler method with Spring MVC Test

Did you try to use a custom ExceptionHandler like here? : https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

If you do so you can return custom HTTP response codes and verify them in your test.