Spring MVC测试中的空异常体

时间:2015-02-04 15:24:15

标签: spring spring-mvc exception-handling spring-mvc-test

我在尝试让MockMvc在响应正文中包含异常消息时遇到了麻烦。我有一个控制器如下:

@RequestMapping("/user/new")
public AbstractResponse create(@Valid NewUserParameters params, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) throw BadRequestException.of(bindingResult);
    // ...
}

BadRequestException看起来像这样:

@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "bad request")
public class BadRequestException extends IllegalArgumentException {

    public BadRequestException(String cause) { super(cause); }

    public static BadRequestException of(BindingResult bindingResult) { /* ... */ }

}

我对/user/new控制器运行以下测试:

@Test
public void testUserNew() throws Exception {
    getMockMvc().perform(post("/user/new")
            .param("username", username)
            .param("password", password))
            .andDo(print())
            .andExpect(status().isOk());
}

打印以下输出:

  Resolved Exception:
                Type = controller.exception.BadRequestException

        ModelAndView:
           View name = null
                View = null
               Model = null

            FlashMap:

MockHttpServletResponse:
              Status = 400
       Error message = bad request
             Headers = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY]}
        Content type = null
                Body = 
       Forwarded URL = null
      Redirected URL = null
             Cookies = []

是否有人知道Body输出中为什么print()丢失?

编辑:我没有使用任何自定义异常处理程序,并且在运行服务器时代码按预期工作。也就是说,运行应用程序并向服务器发出相同的请求将返回

{"timestamp":1423076185822,
 "status":400,
 "error":"Bad Request",
 "exception":"controller.exception.BadRequestException",
 "message":"binding failed for field(s): password, username, username",
 "path":"/user/new"}

正如所料。因此,我认为MockMvc存在问题。它以某种方式错过捕获异常的message字段,而常规应用程序服务器的默认异常处理程序按预期工作。

3 个答案:

答案 0 :(得分:8)

在打开问题的ticket之后,我被告知正文中的错误消息由Spring Boot处理,它在Servlet容器级别配置错误映射,并且因为Spring MVC Test运行了一个模拟Servlet请求/响应,没有这样的错误映射。此外,他们建议我至少创建一个@WebIntegrationTest并坚持使用Spring MVC Test作为我的控制器逻辑。

最终,我决定使用我自己的自定义异常处理程序,并像以前一样坚持MockMvc

@ControllerAdvice
public class CustomExceptionHandler {

    @ExceptionHandler(Throwable.class)
    public @ResponseBody
    ExceptionResponse handle(HttpServletResponse response, Throwable throwable) {
        HttpStatus status = Optional
                .ofNullable(AnnotationUtils.getAnnotation(throwable.getClass(), ResponseStatus.class))
                .map(ResponseStatus::value)
                .orElse(HttpStatus.INTERNAL_SERVER_ERROR);
        response.setStatus(status.value());
        return new ExceptionResponse(throwable.getMessage());
    }

}

@Data
public class ExceptionResponse extends AbstractResponse {

    private final long timestamp = System.currentTimeMillis();

    private final String message;

    @JsonCreator
    public ExceptionResponse(String message) {
        checkNotNull(message, "message == NULL");
        this.message = message;
    }

}

答案 1 :(得分:3)

这可能意味着你要么没有处理异常,要么你真的把身体留空了。要处理异常,请在控制器中添加错误处理程序

@ExceptionHandler
public @ResponseBody String handle(BadRequestException e) {
    return "I'm the body";
}

如果您使用3.2或以上

,请使用全局错误处理程序
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public @ResponseBody String handleBadRequestException(BadRequestException ex) {
        return "I'm the body";
    }
}

使用此主体将填充,您应该使用您的错误消息填充它

答案 2 :(得分:0)

更新的解决方案:

如果您不想进行完整的集成测试,但仍然希望确保消息符合预期,则仍然可以执行以下操作:

String errorMessage = getMockMvc()
                        .perform(post("/user/new"))
                        ...
                        .andReturn().getResolvedException().getMessage();

assertThat(errorMessage, is("This is the error message!");