Testing Spring MVC @ExceptionHandler method with Spring MVC Test

前端 未结 7 1818
悲&欢浪女
悲&欢浪女 2020-12-04 20:56

I have the following simple controller to catch any unexpected exceptions:

@ControllerAdvice
public class ExceptionController {

    @ExceptionHandler(Throwa         


        
7条回答
  •  攒了一身酷
    2020-12-04 21:49

    This code will add ability to use your exceptions controlled advice.

    @Before
    public void setup() {
        this.mockMvc = standaloneSetup(commandsController)
            .setHandlerExceptionResolvers(withExceptionControllerAdvice())
            .setMessageConverters(new MappingJackson2HttpMessageConverter()).build();
    }
    
    private ExceptionHandlerExceptionResolver withExceptionControllerAdvice() {
        final ExceptionHandlerExceptionResolver exceptionResolver = new ExceptionHandlerExceptionResolver() {
            @Override
            protected ServletInvocableHandlerMethod getExceptionHandlerMethod(final HandlerMethod handlerMethod,
                final Exception exception) {
                Method method = new ExceptionHandlerMethodResolver(ExceptionController.class).resolveMethod(exception);
                if (method != null) {
                    return new ServletInvocableHandlerMethod(new ExceptionController(), method);
                }
                return super.getExceptionHandlerMethod(handlerMethod, exception);
            }
        };
        exceptionResolver.afterPropertiesSet();
        return exceptionResolver;
    }
    

提交回复
热议问题