I've written a controller class with an endpoint that accepts a header as part of its request
@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
}
...
}
The endpoint is working fine but I'd like to test its behavior when a header with a null value is supplied. I'd also like to code the getMyObject
method in such a way that it prevents null values from being passed into the header and will return a warning saying that the header field cannot be empty. I've tried to test this using an integration test with a MockMvc
get()
on the endpoint but if I grant a null value to the header as part of that get request the test fails as it says "values cannot be empty". Is it possible to use JSR-303 validation methods here? ie @Valid
and @NotNull
?
I think the parametrized request header should work for you.
Try declaring your method like this.
@GetMapping("<path-to-the-endpoint>")
public MyObject getMyObject(@RequestHeader(value="headerName") String headerName) {
//do something with the header here
}
To test this, you can add a header in your MockMvc.
post("/your end point").header("headerName", "userId")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.