Ignore null header value in MockHttpServletResponse

Prior to this commit, calls to setHeader() and addHeader() in
MockHttpServletResponse would result in an IllegalArgumentException or
NullPointerException if the supplied header value was null.

Although the Javadoc for setHeader(String, String) and
addHeader(String, String) in javax.servlet.http.HttpServletResponse
does not specify how a null header value should be handled, both Tomcat
and Jetty simply ignore a null value. Furthermore,
org.springframework.http.HttpHeaders.add(String, String) declares the
headerValue parameter as @Nullable.

This commit therefore updates MockHttpServletResponse to silently
ignore null header values passed to setHeader() and addHeader().

Closes gh-26488
This commit is contained in:
Sam Brannen
2021-02-02 11:05:06 +01:00
parent c82a445094
commit 3b4a3431d4
3 changed files with 53 additions and 13 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,6 +26,8 @@ import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.web.util.WebUtils;
@@ -57,6 +59,32 @@ class MockHttpServletResponseTests {
private MockHttpServletResponse response = new MockHttpServletResponse();
@ParameterizedTest // gh-26488
@ValueSource(strings = {
CONTENT_TYPE,
CONTENT_LENGTH,
CONTENT_LANGUAGE,
SET_COOKIE,
"enigma"
})
void addHeaderWithNullValue(String headerName) {
response.addHeader(headerName, null);
assertThat(response.containsHeader(headerName)).isFalse();
}
@ParameterizedTest // gh-26488
@ValueSource(strings = {
CONTENT_TYPE,
CONTENT_LENGTH,
CONTENT_LANGUAGE,
SET_COOKIE,
"enigma"
})
void setHeaderWithNullValue(String headerName) {
response.setHeader(headerName, null);
assertThat(response.containsHeader(headerName)).isFalse();
}
@Test
void setContentType() {
String contentType = "test/plain";