Improve handling of parameters with null values

Closes gh-199
This commit is contained in:
Andy Wilkinson
2016-05-24 16:39:57 +01:00
parent 6935f603f2
commit cb1f98c601
2 changed files with 81 additions and 0 deletions

View File

@@ -22,6 +22,7 @@ import java.util.List;
import java.util.Map;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.StringUtils;
/**
* The parameters received in a request.
@@ -68,6 +69,9 @@ public class Parameters extends LinkedMultiValueMap<String, String> {
}
private static String urlEncodeUTF8(String s) {
if (!StringUtils.hasLength(s)) {
return "";
}
try {
return URLEncoder.encode(s, "UTF-8");
}

View File

@@ -0,0 +1,77 @@
/*
* Copyright 2014-2016 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.restdocs.operation;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* Tests for {@link Parameters}.
*
* @author Andy Wilkinson
*/
public class ParametersTests {
private final Parameters parameters = new Parameters();
@Test
public void queryStringForNoParameters() {
assertThat(this.parameters.toQueryString(), is(equalTo("")));
}
@Test
public void queryStringForSingleParameter() {
this.parameters.add("a", "b");
assertThat(this.parameters.toQueryString(), is(equalTo("a=b")));
}
@Test
public void queryStringForSingleParameterWithMultipleValues() {
this.parameters.add("a", "b");
this.parameters.add("a", "c");
assertThat(this.parameters.toQueryString(), is(equalTo("a=b&a=c")));
}
@Test
public void queryStringForMutipleParameters() {
this.parameters.add("a", "alpha");
this.parameters.add("b", "bravo");
assertThat(this.parameters.toQueryString(), is(equalTo("a=alpha&b=bravo")));
}
@Test
public void queryStringForParameterWithEmptyValue() {
this.parameters.add("a", "");
assertThat(this.parameters.toQueryString(), is(equalTo("a=")));
}
@Test
public void queryStringForParameterWithNullValue() {
this.parameters.add("a", null);
assertThat(this.parameters.toQueryString(), is(equalTo("a=")));
}
@Test
public void queryStringForParameterThatRequiresEncoding() {
this.parameters.add("a", "alpha&bravo");
assertThat(this.parameters.toQueryString(), is(equalTo("a=alpha%26bravo")));
}
}