|
| 1 | +package org.baeldung.uribuilder; |
| 2 | + |
| 3 | +import static org.junit.Assert.assertEquals; |
| 4 | + |
| 5 | +import java.util.Collections; |
| 6 | + |
| 7 | +import org.junit.Test; |
| 8 | +import org.springframework.web.util.UriComponents; |
| 9 | +import org.springframework.web.util.UriComponentsBuilder; |
| 10 | + |
| 11 | +public class SpringUriBuilderTest { |
| 12 | + |
| 13 | + @Test |
| 14 | + public void constructUri() { |
| 15 | + UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com") |
| 16 | + .path("/junit-5").build(); |
| 17 | + |
| 18 | + assertEquals("http://www.baeldung.com/junit-5", uriComponents.toUriString()); |
| 19 | + } |
| 20 | + |
| 21 | + @Test |
| 22 | + public void constructUriEncoded() { |
| 23 | + UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com") |
| 24 | + .path("/junit 5").build().encode(); |
| 25 | + |
| 26 | + assertEquals("http://www.baeldung.com/junit%205", uriComponents.toUriString()); |
| 27 | + } |
| 28 | + |
| 29 | + @Test |
| 30 | + public void constructUriFromTemplate() { |
| 31 | + UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com") |
| 32 | + .path("/{article-name}").buildAndExpand("junit-5"); |
| 33 | + |
| 34 | + assertEquals("http://www.baeldung.com/junit-5", uriComponents.toUriString()); |
| 35 | + } |
| 36 | + |
| 37 | + @Test |
| 38 | + public void constructUriWithQueryParameter() { |
| 39 | + UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.google.com") |
| 40 | + .path("/").query("q={keyword}").buildAndExpand("baeldung"); |
| 41 | + |
| 42 | + assertEquals("http://www.google.com/?q=baeldung", uriComponents.toUriString()); |
| 43 | + } |
| 44 | + |
| 45 | + @Test |
| 46 | + public void expandWithRegexVar() { |
| 47 | + String template = "/myurl/{name:[a-z]{1,5}}/show"; |
| 48 | + UriComponents uriComponents = UriComponentsBuilder.fromUriString(template).build(); |
| 49 | + uriComponents = uriComponents.expand(Collections.singletonMap("name", "test")); |
| 50 | + |
| 51 | + assertEquals("/myurl/test/show", uriComponents.getPath()); |
| 52 | + } |
| 53 | +} |
0 commit comments