在控制器中测试抛出的异常 [英] Testing thrown exception in controller

查看:20
本文介绍了在控制器中测试抛出的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对引发异常的控制器方法执行测试.方法是这样的:

I want to perform a test on a controller method which throws an exception. The method is something like this:

@RequestMapping("/do")
public ResponseEntity doIt(@RequestBody Request request) throws Exception {
    throw new NullPointerException();
}

当我尝试使用以下代码部分测试此方法时,

When I try to test this method with following code part,

 mockMvc.perform(post("/do")
                .contentType(MediaType.APPLICATION_JSON)
                .content(JSON.toJson(request)))

NestedServletException 从 Spring 库中抛出.如何测试抛出 NullPointerException 而不是 NestedServletException?

NestedServletException is thrown from Spring libraries. How can I test that NullPointerException is thrown instead of NestedServletException?

推荐答案

我们的解决方案是一种变通方法:异常在通知中捕获,错误正文作为 HTTP 响应返回.这是模拟的工作原理:

Our solution is rather a workaround: The exception is caught in advice and error body is returned as HTTP response. Here is how the mock works:

MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controller)
                        .setHandlerExceptionResolvers(withExceptionControllerAdvice())
                        .build();

private ExceptionHandlerExceptionResolver withExceptionControllerAdvice() {
    final ExceptionHandlerExceptionResolver exceptionResolver = new ExceptionHandlerExceptionResolver() {
        @Override
        protected ServletInvocableHandlerMethod getExceptionHandlerMethod(final HandlerMethod handlerMethod, final Exception exception) {
            Method method = new ExceptionHandlerMethodResolver(TestAdvice.class).resolveMethod(exception);
            if (method != null) {
                return new ServletInvocableHandlerMethod(new TestAdvice(), method);
            }
            return super.getExceptionHandlerMethod(handlerMethod, exception);
        }
    };
    exceptionResolver.afterPropertiesSet();
    return exceptionResolver;
}

咨询类:

@ControllerAdvice
public class TestAdvice {
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Object exceptionHandler(Exception e) {
        return new HttpEntity<>(e.getMessage());
    }
}

之后,以下测试方法成功通过:

After than, following test method passes successfully:

@Test
public void testException
    mockMvc.perform(post("/exception/path"))
        .andExpect(status().is5xxServerError())
        .andExpect(content().string("Exception body"));
}

这篇关于在控制器中测试抛出的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆