如何在@WebMvcTest 中获取 Spring 引导默认验证响应?
How to get Spring Boot default validation reponses in @WebMvcTest?
当我 运行 我的应用程序并且对我的端点之一的请求存在验证问题时,响应包含大量关于到底出了什么问题的信息。它看起来类似于:
{
"timestamp": "2017-11-23T13:18:05.923+0000",
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.web.bind.MethodArgumentNotValidException",
"errors": [
{
"codes": [
"Size.sensorParameters.openText",
"Size.openText",
"Size.java.lang.String",
"Size"
],
"arguments": [
{
"codes": [
"sensorParameters.openText",
"openText"
],
"arguments": null,
"defaultMessage": "openText",
"code": "openText"
},
20,
1
],
"defaultMessage": "size must be between 1 and 20",
"objectName": "sensorParameters",
"field": "openText",
"rejectedValue": "xewrewrwerwer weew ewewewrwe ew wewewewerew we ewrwerwe ewr ",
"bindingFailure": false,
"code": "Size"
}
],
"message": "Validation failed for object='sensorParameters'. Error count: 1",
"path": "/api/monitors/89c94880-9423-4990-892b-6bbd8e90b1e6/sensors"
}
如果我在 @WebMvcTest
中测试它,我会得到相同的 400 响应,但响应正文是空的。
为了在我的单元测试中获得相同的行为,我应该做一些额外的设置吗?我正在使用从测试框架获得的 @Autowired
MockMvc 对象,目前我这边没有任何额外设置。
正如 Rossen Stoyanchev(MockMvc
的发明者)在 JIRA 的相关问题中指出的...
the body is taken care of by Spring Boot which configures error mappings at the Servlet container level (see here and since Spring MVC Test runs with a mock Servlet request/response, there is no such error mapping.
他继续建议一个人使用 MockMvc
来测试控制器逻辑和映射,但是那个人写一个 in container 与 Spring Boot 的集成测试由 Spring Boot.
管理的 Servlet 中的错误映射支持
如果您觉得 Spring Boot 应该以某种方式(神奇地)提供与 MockMvc
一起的错误映射支持,我建议您在 GitHub 上提出问题反对Spring 引导项目。
当我 运行 我的应用程序并且对我的端点之一的请求存在验证问题时,响应包含大量关于到底出了什么问题的信息。它看起来类似于:
{
"timestamp": "2017-11-23T13:18:05.923+0000",
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.web.bind.MethodArgumentNotValidException",
"errors": [
{
"codes": [
"Size.sensorParameters.openText",
"Size.openText",
"Size.java.lang.String",
"Size"
],
"arguments": [
{
"codes": [
"sensorParameters.openText",
"openText"
],
"arguments": null,
"defaultMessage": "openText",
"code": "openText"
},
20,
1
],
"defaultMessage": "size must be between 1 and 20",
"objectName": "sensorParameters",
"field": "openText",
"rejectedValue": "xewrewrwerwer weew ewewewrwe ew wewewewerew we ewrwerwe ewr ",
"bindingFailure": false,
"code": "Size"
}
],
"message": "Validation failed for object='sensorParameters'. Error count: 1",
"path": "/api/monitors/89c94880-9423-4990-892b-6bbd8e90b1e6/sensors"
}
如果我在 @WebMvcTest
中测试它,我会得到相同的 400 响应,但响应正文是空的。
为了在我的单元测试中获得相同的行为,我应该做一些额外的设置吗?我正在使用从测试框架获得的 @Autowired
MockMvc 对象,目前我这边没有任何额外设置。
正如 Rossen Stoyanchev(MockMvc
的发明者)在 JIRA 的相关问题中指出的...
the body is taken care of by Spring Boot which configures error mappings at the Servlet container level (see here and since Spring MVC Test runs with a mock Servlet request/response, there is no such error mapping.
他继续建议一个人使用 MockMvc
来测试控制器逻辑和映射,但是那个人写一个 in container 与 Spring Boot 的集成测试由 Spring Boot.
如果您觉得 Spring Boot 应该以某种方式(神奇地)提供与 MockMvc
一起的错误映射支持,我建议您在 GitHub 上提出问题反对Spring 引导项目。