Add queryParamIfPresent to UriComponentsBuilder

See gh-25951
This commit is contained in:
Robin Roos
2020-10-21 19:18:11 +01:00
committed by Rossen Stoyanchev
parent 51fb49be34
commit 7af726480f
4 changed files with 61 additions and 0 deletions

View File

@@ -18,11 +18,13 @@ package org.springframework.web.util;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.Test;
@@ -204,6 +206,33 @@ class UriComponentsBuilderTests {
assertThat(uri.toString()).isEqualTo(httpUrl);
}
@Test
void queryParamIfPresent() {
UriComponentsBuilder builder = UriComponentsBuilder.newInstance();
UriComponents result = builder.queryParamIfPresent("baz", Optional.of("qux")).queryParamIfPresent("foo", Optional.empty()).build();
assertThat(result.getQuery()).isEqualTo("baz=qux");
MultiValueMap<String, String> expectedQueryParams = new LinkedMultiValueMap<>(1);
expectedQueryParams.add("baz", "qux");
assertThat(result.getQueryParams()).isEqualTo(expectedQueryParams);
}
@Test
void queryParamIfPresentCollection() {
Collection<String> c = new ArrayList<>();
c.add("foo");
c.add("bar");
UriComponentsBuilder builder = UriComponentsBuilder.newInstance();
UriComponents result = builder.queryParamIfPresent("baz", Optional.of(c)).build();
assertThat(result.getQuery()).isEqualTo("baz=foo&baz=bar");
MultiValueMap<String, String> expectedQueryParams = new LinkedMultiValueMap<>(1);
expectedQueryParams.add("baz", "foo");
expectedQueryParams.add("baz", "bar");
assertThat(result.getQueryParams()).isEqualTo(expectedQueryParams);
}
@Test // SPR-10539
void fromUriStringIPv6Host() {
UriComponents result = UriComponentsBuilder