Spring MVC测试中的空异常主体
问题内容:
尝试使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
异常的字段,而常规应用程序服务器的默认异常处理程序按预期工作。
问题答案:
打开后票的问题,有人告诉我,在体内的错误消息由弹簧引导其在Servlet容器水平,因为有一个模拟Servlet的请求/响应Spring
MVC的试运行配置错误映射的照顾,有没有这样的错误映射。此外,他们建议我创建至少一个@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;
}
}