如何在@WebMvcTest中获取Spring Boot默认验证响应?

时间:2017-11-23 13:29:29

标签: java spring spring-boot spring-test

当我运行我的应用程序并且对我的一个端点的请求存在验证问题时,响应有很多关于究竟出错的信息。它看起来与此相似:

{
  "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对象,而我目前没有任何额外的设置。

1 个答案:

答案 0 :(得分:2)

Rossen Stoyanchev(MockMvc的发明者)在JIRA的相关问题中指出......

  

正在由Spring Boot处理主体,它在Servlet容器级别配置错误映射(请参阅here,并且由于Spring MVC Test使用模拟Servlet请求/响应运行,因此没有此类错误映射。< / p>

他接着建议使用MockMvc来测试控制器逻辑和映射,但是那个用容器在容器中与Spring Boot集成来测试Servlet中的错误映射支持由Spring Boot管理。

如果您认为Spring Boot应该以某种方式(神奇地)提供与MockMvc一起提供的错误映射支持,我建议您在GitHub上针对Spring Boot项目提出问题。