Description
Hello,
I've faced an issue recently working with MockHttpServletResponse
. The thing is when I have conditional (value can be null) headers in my controller, and I want to test them using MockMvc
it fails, because MockHttpServletResponse
checks if header value in response is null
.
Below is what I am trying to do:
@GetMapping("/example")
public ResponseEntity<?> example() {
String nullableHeaderValue = conditionalHeaderValue();
return ResponseEntity.ok()
.header("Some-header", nullableHeaderValue)
.body("Hi");
}
So the intention is to send header if its value is present and it works as expected. But when I test it with MockMvc
it throws an IllegalArgumentException
due to this check in MockHttpServletResponse
:
private void doAddHeaderValue(String name, Object value, boolean replace) {
HeaderValueHolder header = this.headers.get(name);
Assert.notNull(value, "Header value must not be null");
if (header == null) {
header = new HeaderValueHolder();
this.headers.put(name, header);
}
if (replace) {
header.setValue(value);
}
else {
header.addValue(value);
}
}
I know that as workaround instead of nullability of value of header I can put headers themselves conditionally, but the thing is that spec of HttpServletResponse
allows me to have nullable header values, while MockHttpServletResponse
does not, and this behavior is surprising to say the least.