【问题标题】:How To Validate RequestHeader For RestAPI Controller Endpoint如何验证 Rest API 控制器端点的请求标头
【发布时间】:2018-10-18 14:42:23
【问题描述】:

我编写了一个控制器类,其端点接受标头作为其请求的一部分

@RestController
@RequestMapping("<mapping-path>")
public class MyController {
...
@GetMapping("<path-to-the-endpoint>")
public MyObject getMyObject(@RequestHeader("headerName") String headerName) {
    //do something with the header here
}
...
}

端点工作正常,但我想在提供具有空值的标头时测试其行为。我还想以这样一种方式对getMyObject 方法进行编码,以防止将空值传递到标头中,并返回一个警告,指出标头字段不能为空。我尝试在端点上使用带有MockMvcget() 的集成测试对此进行测试,但是如果我将空值作为该获取请求的一部分授予标头,则测试失败,因为它说“值不能为空” .是否可以在这里使用 JSR-303 验证方法?即@Valid@NotNull?

【问题讨论】:

    标签: java rest spring-boot bean-validation request-headers


    【解决方案1】:

    我认为参数化的请求标头应该适合你。

    尝试像这样声明你的方法。

    @GetMapping("<path-to-the-endpoint>")
    public MyObject getMyObject(@RequestHeader(value="headerName") String headerName) {
        //do something with the header here
    }
    

    要对此进行测试,您可以在 MockMvc 中添加标头。

    post("/your end point").header("headerName", "userId")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-24
      • 1970-01-01
      • 1970-01-01
      • 2021-08-11
      • 1970-01-01
      • 2018-03-23
      • 2021-06-02
      相关资源
      最近更新 更多