CustomAccessDeniedHandler implements AccessDeniedHandler { @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException { response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.getWriter().println(objectMapper.writeValueAsString(new ErrorResponseEntityBody("forbidden"))); response.flushBuffer(); }  @Override void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException accessDeniedException);  }
@Test public void customAccessDeniedHandlerShouldRespondAsExpected() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); customAccessDeniedHandler.handle(request, response, new AccessDeniedException("access denied")); ErrorResponseEntityBody responseEntityBody = objectMapper.readValue(response.getContentAsByteArray(), ErrorResponseEntityBody.class); assertThat(response.isCommitted()).isTrue(); assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN); assertThat(response.getContentType()).isEqualTo(MediaType.APPLICATION_JSON_VALUE); assertThat(responseEntityBody.getError()).isEqualTo("forbidden"); }