Polishing

This commit is contained in:
Sam Brannen 2022-11-08 19:22:10 +01:00
parent debe78b7f9
commit 7d68d0625c
24 changed files with 257 additions and 271 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2022 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.

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 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.

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2022 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.

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2022 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.

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 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.

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 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.
@ -16,8 +16,6 @@
package org.springframework.test.context.junit4.spr9051;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
@ -93,9 +91,8 @@ public class AnnotatedConfigClassesWithoutAtConfigurationTests {
assertThat(enigma).isNotNull();
assertThat(lifecycleBean).isNotNull();
assertThat(lifecycleBean.isInitialized()).isTrue();
Set<String> names = new HashSet<>();
names.add(enigma);
names.add(lifecycleBean.getName());
assertThat(new HashSet<>(Arrays.asList("enigma #1", "enigma #2"))).isEqualTo(names);
Set<String> names = Set.of(enigma, lifecycleBean.getName());
assertThat(names).containsExactlyInAnyOrder("enigma #1", "enigma #2");
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 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.

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 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.

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2022 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.
@ -38,13 +38,13 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat
*
* @author Rossen Stoyanchev
*/
public class MockRestServiceServerTests {
class MockRestServiceServerTests {
private final RestTemplate restTemplate = new RestTemplate();
@Test
public void buildMultipleTimes() {
void buildMultipleTimes() {
MockRestServiceServerBuilder builder = MockRestServiceServer.bindTo(this.restTemplate);
MockRestServiceServer server = builder.build();
@ -66,7 +66,7 @@ public class MockRestServiceServerTests {
}
@Test
public void exactExpectOrder() {
void exactExpectOrder() {
MockRestServiceServer server = MockRestServiceServer.bindTo(this.restTemplate)
.ignoreExpectOrder(false).build();
@ -77,7 +77,7 @@ public class MockRestServiceServerTests {
}
@Test
public void ignoreExpectOrder() {
void ignoreExpectOrder() {
MockRestServiceServer server = MockRestServiceServer.bindTo(this.restTemplate)
.ignoreExpectOrder(true).build();
@ -89,7 +89,7 @@ public class MockRestServiceServerTests {
}
@Test
public void resetAndReuseServer() {
void resetAndReuseServer() {
MockRestServiceServer server = MockRestServiceServer.bindTo(this.restTemplate).build();
server.expect(requestTo("/foo")).andRespond(withSuccess());
@ -103,7 +103,7 @@ public class MockRestServiceServerTests {
}
@Test
public void resetAndReuseServerWithUnorderedExpectationManager() {
void resetAndReuseServerWithUnorderedExpectationManager() {
MockRestServiceServer server = MockRestServiceServer.bindTo(this.restTemplate)
.ignoreExpectOrder(true).build();
@ -120,7 +120,7 @@ public class MockRestServiceServerTests {
}
@Test // gh-24486
public void resetClearsRequestFailures() {
void resetClearsRequestFailures() {
MockRestServiceServer server = MockRestServiceServer.bindTo(this.restTemplate).build();
server.expect(once(), requestTo("/remoteurl")).andRespond(withSuccess());
this.restTemplate.postForEntity("/remoteurl", null, String.class);
@ -138,7 +138,7 @@ public class MockRestServiceServerTests {
}
@Test // SPR-16132
public void followUpRequestAfterFailure() {
void followUpRequestAfterFailure() {
MockRestServiceServer server = MockRestServiceServer.bindTo(this.restTemplate).build();
server.expect(requestTo("/some-service/some-endpoint"))
@ -159,7 +159,7 @@ public class MockRestServiceServerTests {
}
@Test // gh-21799
public void verifyShouldFailIfRequestsFailed() {
void verifyShouldFailIfRequestsFailed() {
MockRestServiceServer server = MockRestServiceServer.bindTo(this.restTemplate).build();
server.expect(once(), requestTo("/remoteurl")).andRespond(withSuccess());
@ -174,7 +174,7 @@ public class MockRestServiceServerTests {
}
@Test
public void verifyWithTimeout() {
void verifyWithTimeout() {
MockRestServiceServerBuilder builder = MockRestServiceServer.bindTo(this.restTemplate);
MockRestServiceServer server1 = builder.build();
@ -182,12 +182,11 @@ public class MockRestServiceServerTests {
server1.expect(requestTo("/bar")).andRespond(withSuccess());
this.restTemplate.getForObject("/foo", Void.class);
assertThatThrownBy(() -> server1.verify(Duration.ofMillis(100))).hasMessage(
"""
Further request(s) expected leaving 1 unsatisfied expectation(s).
1 request(s) executed:
GET /foo, headers: [Accept:"application/json, application/*+json"]
""");
assertThatThrownBy(() -> server1.verify(Duration.ofMillis(100))).hasMessage("""
Further request(s) expected leaving 1 unsatisfied expectation(s).
1 request(s) executed:
GET /foo, headers: [Accept:"application/json, application/*+json"]
""");
MockRestServiceServer server2 = builder.build();
server2.expect(requestTo("/foo")).andRespond(withSuccess());

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 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,7 +26,6 @@ import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.mock.http.client.MockClientHttpRequest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.http.HttpMethod.GET;
import static org.springframework.http.HttpMethod.POST;
@ -44,31 +43,28 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat
*
* @author Rossen Stoyanchev
*/
public class SimpleRequestExpectationManagerTests {
class SimpleRequestExpectationManagerTests {
private final SimpleRequestExpectationManager manager = new SimpleRequestExpectationManager();
@Test
public void unexpectedRequest() throws Exception {
try {
this.manager.validateRequest(createRequest(GET, "/foo"));
}
catch (AssertionError error) {
assertThat(error.getMessage()).isEqualTo(("""
void unexpectedRequest() throws Exception {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> this.manager.validateRequest(createRequest(GET, "/foo")))
.withMessage("""
No further requests expected: HTTP GET /foo
0 request(s) executed.
"""));
}
""");
}
@Test
public void zeroExpectedRequests() throws Exception {
void zeroExpectedRequests() throws Exception {
this.manager.verify();
}
@Test
public void sequentialRequests() throws Exception {
void sequentialRequests() throws Exception {
this.manager.expectRequest(once(), requestTo("/foo")).andExpect(method(GET)).andRespond(withSuccess());
this.manager.expectRequest(once(), requestTo("/bar")).andExpect(method(GET)).andRespond(withSuccess());
@ -78,13 +74,13 @@ public class SimpleRequestExpectationManagerTests {
}
@Test
public void sequentialRequestsTooMany() throws Exception {
void sequentialRequestsTooMany() throws Exception {
this.manager.expectRequest(max(1), requestTo("/foo")).andExpect(method(GET)).andRespond(withSuccess());
this.manager.expectRequest(max(1), requestTo("/bar")).andExpect(method(GET)).andRespond(withSuccess());
this.manager.validateRequest(createRequest(GET, "/foo"));
this.manager.validateRequest(createRequest(GET, "/bar"));
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.manager.validateRequest(createRequest(GET, "/baz")))
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> this.manager.validateRequest(createRequest(GET, "/baz")))
.withMessage("""
No further requests expected: HTTP GET /baz
2 request(s) executed:
@ -94,12 +90,12 @@ public class SimpleRequestExpectationManagerTests {
}
@Test
public void sequentialRequestsTooFew() throws Exception {
void sequentialRequestsTooFew() throws Exception {
this.manager.expectRequest(min(1), requestTo("/foo")).andExpect(method(GET)).andRespond(withSuccess());
this.manager.expectRequest(min(1), requestTo("/bar")).andExpect(method(GET)).andRespond(withSuccess());
this.manager.validateRequest(createRequest(GET, "/foo"));
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.manager.verify())
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> this.manager.verify())
.withMessage("""
Further request(s) expected leaving 1 unsatisfied expectation(s).
1 request(s) executed:
@ -108,7 +104,7 @@ public class SimpleRequestExpectationManagerTests {
}
@Test
public void repeatedRequests() throws Exception {
void repeatedRequests() throws Exception {
this.manager.expectRequest(times(3), requestTo("/foo")).andExpect(method(GET)).andRespond(withSuccess());
this.manager.expectRequest(times(3), requestTo("/bar")).andExpect(method(GET)).andRespond(withSuccess());
@ -122,15 +118,15 @@ public class SimpleRequestExpectationManagerTests {
}
@Test
public void repeatedRequestsTooMany() throws Exception {
void repeatedRequestsTooMany() throws Exception {
this.manager.expectRequest(max(2), requestTo("/foo")).andExpect(method(GET)).andRespond(withSuccess());
this.manager.expectRequest(max(2), requestTo("/bar")).andExpect(method(GET)).andRespond(withSuccess());
this.manager.validateRequest(createRequest(GET, "/foo"));
this.manager.validateRequest(createRequest(GET, "/bar"));
this.manager.validateRequest(createRequest(GET, "/foo"));
this.manager.validateRequest(createRequest(GET, "/bar"));
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.manager.validateRequest(createRequest(GET, "/foo")))
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> this.manager.validateRequest(createRequest(GET, "/foo")))
.withMessage("""
No further requests expected: HTTP GET /foo
4 request(s) executed:
@ -142,14 +138,14 @@ public class SimpleRequestExpectationManagerTests {
}
@Test
public void repeatedRequestsTooFew() throws Exception {
void repeatedRequestsTooFew() throws Exception {
this.manager.expectRequest(min(2), requestTo("/foo")).andExpect(method(GET)).andRespond(withSuccess());
this.manager.expectRequest(min(2), requestTo("/bar")).andExpect(method(GET)).andRespond(withSuccess());
this.manager.validateRequest(createRequest(GET, "/foo"));
this.manager.validateRequest(createRequest(GET, "/bar"));
this.manager.validateRequest(createRequest(GET, "/foo"));
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.manager.verify())
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> this.manager.verify())
.withMessageContaining("""
3 request(s) executed:
GET /foo
@ -159,17 +155,17 @@ public class SimpleRequestExpectationManagerTests {
}
@Test
public void repeatedRequestsNotInOrder() throws Exception {
void repeatedRequestsNotInOrder() throws Exception {
this.manager.expectRequest(twice(), requestTo("/foo")).andExpect(method(GET)).andRespond(withSuccess());
this.manager.expectRequest(twice(), requestTo("/bar")).andExpect(method(GET)).andRespond(withSuccess());
this.manager.expectRequest(twice(), requestTo("/baz")).andExpect(method(GET)).andRespond(withSuccess());
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.manager.validateRequest(createRequest(POST, "/foo")))
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> this.manager.validateRequest(createRequest(POST, "/foo")))
.withMessage("Unexpected HttpMethod expected:<GET> but was:<POST>");
}
@Test // SPR-15672
public void sequentialRequestsWithDifferentCount() throws Exception {
void sequentialRequestsWithDifferentCount() throws Exception {
this.manager.expectRequest(times(2), requestTo("/foo")).andExpect(method(GET)).andRespond(withSuccess());
this.manager.expectRequest(once(), requestTo("/bar")).andExpect(method(GET)).andRespond(withSuccess());
@ -179,7 +175,7 @@ public class SimpleRequestExpectationManagerTests {
}
@Test // SPR-15719
public void repeatedRequestsInSequentialOrder() throws Exception {
void repeatedRequestsInSequentialOrder() throws Exception {
this.manager.expectRequest(times(2), requestTo("/foo")).andExpect(method(GET)).andRespond(withSuccess());
this.manager.expectRequest(times(2), requestTo("/bar")).andExpect(method(GET)).andRespond(withSuccess());
@ -190,7 +186,7 @@ public class SimpleRequestExpectationManagerTests {
}
@Test // SPR-16132
public void sequentialRequestsWithFirstFailing() throws Exception {
void sequentialRequestsWithFirstFailing() throws Exception {
this.manager.expectRequest(once(), requestTo("/foo")).
andExpect(method(GET)).andRespond(request -> { throw new SocketException("pseudo network error"); });
this.manager.expectRequest(once(), requestTo("/handle-error")).

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 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.
@ -25,7 +25,6 @@ import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.mock.http.client.MockClientHttpRequest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.http.HttpMethod.GET;
import static org.springframework.test.web.client.ExpectedCount.max;
@ -41,31 +40,28 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat
*
* @author Rossen Stoyanchev
*/
public class UnorderedRequestExpectationManagerTests {
class UnorderedRequestExpectationManagerTests {
private final UnorderedRequestExpectationManager manager = new UnorderedRequestExpectationManager();
@Test
public void unexpectedRequest() throws Exception {
try {
this.manager.validateRequest(createRequest(GET, "/foo"));
}
catch (AssertionError error) {
assertThat(error.getMessage()).isEqualTo(("""
void unexpectedRequest() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> this.manager.validateRequest(createRequest(GET, "/foo")))
.withMessage("""
No further requests expected: HTTP GET /foo
0 request(s) executed.
"""));
}
""");
}
@Test
public void zeroExpectedRequests() {
void zeroExpectedRequests() {
this.manager.verify();
}
@Test
public void multipleRequests() throws Exception {
void multipleRequests() throws Exception {
this.manager.expectRequest(once(), requestTo("/foo")).andExpect(method(GET)).andRespond(withSuccess());
this.manager.expectRequest(once(), requestTo("/bar")).andExpect(method(GET)).andRespond(withSuccess());
@ -75,7 +71,7 @@ public class UnorderedRequestExpectationManagerTests {
}
@Test
public void repeatedRequests() throws Exception {
void repeatedRequests() throws Exception {
this.manager.expectRequest(twice(), requestTo("/foo")).andExpect(method(GET)).andRespond(withSuccess());
this.manager.expectRequest(twice(), requestTo("/bar")).andExpect(method(GET)).andRespond(withSuccess());
@ -87,15 +83,15 @@ public class UnorderedRequestExpectationManagerTests {
}
@Test
public void repeatedRequestsTooMany() throws Exception {
void repeatedRequestsTooMany() throws Exception {
this.manager.expectRequest(max(2), requestTo("/foo")).andExpect(method(GET)).andRespond(withSuccess());
this.manager.expectRequest(max(2), requestTo("/bar")).andExpect(method(GET)).andRespond(withSuccess());
this.manager.validateRequest(createRequest(GET, "/bar"));
this.manager.validateRequest(createRequest(GET, "/foo"));
this.manager.validateRequest(createRequest(GET, "/bar"));
this.manager.validateRequest(createRequest(GET, "/foo"));
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.manager.validateRequest(createRequest(GET, "/foo")))
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> this.manager.validateRequest(createRequest(GET, "/foo")))
.withMessage("""
No further requests expected: HTTP GET /foo
4 request(s) executed:
@ -107,20 +103,20 @@ public class UnorderedRequestExpectationManagerTests {
}
@Test
public void repeatedRequestsTooFew() throws Exception {
void repeatedRequestsTooFew() throws Exception {
this.manager.expectRequest(min(2), requestTo("/foo")).andExpect(method(GET)).andRespond(withSuccess());
this.manager.expectRequest(min(2), requestTo("/bar")).andExpect(method(GET)).andRespond(withSuccess());
this.manager.validateRequest(createRequest(GET, "/bar"));
this.manager.validateRequest(createRequest(GET, "/foo"));
this.manager.validateRequest(createRequest(GET, "/foo"));
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(this.manager::verify)
.withMessageContaining("""
3 request(s) executed:
GET /bar
GET /foo
GET /foo
""");
.isThrownBy(this.manager::verify)
.withMessageContaining("""
3 request(s) executed:
GET /bar
GET /foo
GET /foo
""");
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2022 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.

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2022 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.
@ -17,7 +17,6 @@
package org.springframework.test.web.servlet.htmlunit;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import com.gargoylesoftware.htmlunit.HttpWebConnection;
@ -39,6 +38,7 @@ import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.htmlunit.DelegatingWebConnection.DelegateWebConnection;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
@ -52,7 +52,7 @@ import static org.springframework.core.testfixture.TestGroup.LONG_RUNNING;
* @since 4.2
*/
@ExtendWith(MockitoExtension.class)
public class DelegatingWebConnectionTests {
class DelegatingWebConnectionTests {
private DelegatingWebConnection webConnection;
@ -78,9 +78,9 @@ public class DelegatingWebConnectionTests {
@BeforeEach
public void setup() throws Exception {
void setup() throws Exception {
request = new WebRequest(new URL("http://localhost/"));
WebResponseData data = new WebResponseData("".getBytes(StandardCharsets.UTF_8), 200, "", Collections.emptyList());
WebResponseData data = new WebResponseData("".getBytes(UTF_8), 200, "", Collections.emptyList());
expectedResponse = new WebResponse(data, request, 100L);
webConnection = new DelegatingWebConnection(defaultConnection,
new DelegateWebConnection(matcher1, connection1), new DelegateWebConnection(matcher2, connection2));
@ -88,7 +88,7 @@ public class DelegatingWebConnectionTests {
@Test
public void getResponseDefault() throws Exception {
void getResponseDefault() throws Exception {
given(defaultConnection.getResponse(request)).willReturn(expectedResponse);
WebResponse response = webConnection.getResponse(request);
@ -100,7 +100,7 @@ public class DelegatingWebConnectionTests {
}
@Test
public void getResponseAllMatches() throws Exception {
void getResponseAllMatches() throws Exception {
given(matcher1.matches(request)).willReturn(true);
given(connection1.getResponse(request)).willReturn(expectedResponse);
WebResponse response = webConnection.getResponse(request);
@ -112,7 +112,7 @@ public class DelegatingWebConnectionTests {
}
@Test
public void getResponseSecondMatches() throws Exception {
void getResponseSecondMatches() throws Exception {
given(matcher2.matches(request)).willReturn(true);
given(connection2.getResponse(request)).willReturn(expectedResponse);
WebResponse response = webConnection.getResponse(request);
@ -126,7 +126,7 @@ public class DelegatingWebConnectionTests {
@Test
@EnabledForTestGroups(LONG_RUNNING)
public void verifyExampleInClassLevelJavadoc() throws Exception {
void verifyExampleInClassLevelJavadoc() throws Exception {
WebClient webClient = new WebClient();
MockMvc mockMvc = MockMvcBuilders.standaloneSetup().build();

View File

@ -19,7 +19,6 @@ package org.springframework.test.web.servlet.request;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
@ -34,7 +33,6 @@ import jakarta.servlet.http.Cookie;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
@ -46,8 +44,12 @@ import org.springframework.web.servlet.FlashMap;
import org.springframework.web.servlet.support.SessionFlashMapManager;
import org.springframework.web.util.UriComponentsBuilder;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.springframework.http.HttpMethod.GET;
import static org.springframework.http.HttpMethod.POST;
/**
* Unit tests for building a {@link MockHttpServletRequest} with
@ -60,7 +62,7 @@ class MockHttpServletRequestBuilderTests {
private final ServletContext servletContext = new MockServletContext();
private MockHttpServletRequestBuilder builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/foo/bar");
private MockHttpServletRequestBuilder builder = new MockHttpServletRequestBuilder(GET, "/foo/bar");
@Test
@ -73,7 +75,7 @@ class MockHttpServletRequestBuilderTests {
@Test
void uri() {
String uri = "https://java.sun.com:8080/javase/6/docs/api/java/util/BitSet.html?foo=bar#and(java.util.BitSet)";
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, uri);
this.builder = new MockHttpServletRequestBuilder(GET, uri);
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertThat(request.getScheme()).isEqualTo("https");
@ -87,7 +89,7 @@ class MockHttpServletRequestBuilderTests {
@Test
void requestUriWithEncoding() {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/foo bar");
this.builder = new MockHttpServletRequestBuilder(GET, "/foo bar");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertThat(request.getRequestURI()).isEqualTo("/foo%20bar");
@ -95,7 +97,7 @@ class MockHttpServletRequestBuilderTests {
@Test // SPR-13435
void requestUriWithDoubleSlashes() throws URISyntaxException {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, new URI("/test//currentlyValid/0"));
this.builder = new MockHttpServletRequestBuilder(GET, new URI("/test//currentlyValid/0"));
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertThat(request.getRequestURI()).isEqualTo("/test//currentlyValid/0");
@ -109,7 +111,7 @@ class MockHttpServletRequestBuilderTests {
@Test
void contextPathEmpty() {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/foo");
this.builder = new MockHttpServletRequestBuilder(GET, "/foo");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertThat(request.getContextPath()).isEqualTo("");
@ -119,7 +121,7 @@ class MockHttpServletRequestBuilderTests {
@Test
void contextPathServletPathEmpty() {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/travel/hotels/42");
this.builder = new MockHttpServletRequestBuilder(GET, "/travel/hotels/42");
this.builder.contextPath("/travel");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
@ -130,7 +132,7 @@ class MockHttpServletRequestBuilderTests {
@Test
void contextPathServletPath() {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/travel/main/hotels/42");
this.builder = new MockHttpServletRequestBuilder(GET, "/travel/main/hotels/42");
this.builder.contextPath("/travel");
this.builder.servletPath("/main");
@ -143,7 +145,7 @@ class MockHttpServletRequestBuilderTests {
@Test
void contextPathServletPathInfoEmpty() {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/travel/hotels/42");
this.builder = new MockHttpServletRequestBuilder(GET, "/travel/hotels/42");
this.builder.contextPath("/travel");
this.builder.servletPath("/hotels/42");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
@ -155,7 +157,7 @@ class MockHttpServletRequestBuilderTests {
@Test
void contextPathServletPathInfo() {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/");
this.builder = new MockHttpServletRequestBuilder(GET, "/");
this.builder.servletPath("/index.html");
this.builder.pathInfo(null);
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
@ -167,7 +169,7 @@ class MockHttpServletRequestBuilderTests {
@Test // gh-28823
void emptyPath() {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "");
this.builder = new MockHttpServletRequestBuilder(GET, "");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertThat(request.getRequestURI()).isEqualTo("");
@ -178,7 +180,7 @@ class MockHttpServletRequestBuilderTests {
@Test // SPR-16453
void pathInfoIsDecoded() {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/travel/hotels 42");
this.builder = new MockHttpServletRequestBuilder(GET, "/travel/hotels 42");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertThat(request.getPathInfo()).isEqualTo("/travel/hotels 42");
@ -208,7 +210,7 @@ class MockHttpServletRequestBuilderTests {
@Test
void requestUriAndFragment() {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/foo#bar");
this.builder = new MockHttpServletRequestBuilder(GET, "/foo#bar");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertThat(request.getRequestURI()).isEqualTo("/foo");
@ -226,7 +228,7 @@ class MockHttpServletRequestBuilderTests {
@Test
void requestParameterFromQuery() {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/?foo=bar&foo=baz");
this.builder = new MockHttpServletRequestBuilder(GET, "/?foo=bar&foo=baz");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
Map<String, String[]> parameterMap = request.getParameterMap();
@ -237,7 +239,7 @@ class MockHttpServletRequestBuilderTests {
@Test
void requestParameterFromQueryList() {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/?foo[0]=bar&foo[1]=baz");
this.builder = new MockHttpServletRequestBuilder(GET, "/?foo[0]=bar&foo[1]=baz");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
@ -248,7 +250,7 @@ class MockHttpServletRequestBuilderTests {
@Test
void queryParameter() {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/");
this.builder = new MockHttpServletRequestBuilder(GET, "/");
this.builder.queryParam("foo", "bar");
this.builder.queryParam("foo", "baz");
@ -260,7 +262,7 @@ class MockHttpServletRequestBuilderTests {
@Test
void queryParameterMap() {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/");
this.builder = new MockHttpServletRequestBuilder(GET, "/");
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>();
List<String> values = new ArrayList<>();
values.add("bar");
@ -276,7 +278,7 @@ class MockHttpServletRequestBuilderTests {
@Test
void queryParameterList() {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/");
this.builder = new MockHttpServletRequestBuilder(GET, "/");
this.builder.queryParam("foo[0]", "bar");
this.builder.queryParam("foo[1]", "baz");
@ -289,7 +291,7 @@ class MockHttpServletRequestBuilderTests {
@Test
void requestParameterFromQueryWithEncoding() {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/?foo={value}", "bar=baz");
this.builder = new MockHttpServletRequestBuilder(GET, "/?foo={value}", "bar=baz");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
@ -299,7 +301,7 @@ class MockHttpServletRequestBuilderTests {
@Test // SPR-11043
void requestParameterFromQueryNull() {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/?foo");
this.builder = new MockHttpServletRequestBuilder(GET, "/?foo");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
Map<String, String[]> parameterMap = request.getParameterMap();
@ -313,7 +315,7 @@ class MockHttpServletRequestBuilderTests {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("foo", "bar");
params.add("foo", "baz");
this.builder = new MockHttpServletRequestBuilder(HttpMethod.POST, "/foo");
this.builder = new MockHttpServletRequestBuilder(POST, "/foo");
this.builder.params(params);
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
@ -326,8 +328,8 @@ class MockHttpServletRequestBuilderTests {
String contentType = "application/x-www-form-urlencoded;charset=UTF-8";
String body = "name+1=value+1&name+2=value+A&name+2=value+B&name+3";
MockHttpServletRequest request = new MockHttpServletRequestBuilder(HttpMethod.POST, "/foo")
.contentType(contentType).content(body.getBytes(StandardCharsets.UTF_8))
MockHttpServletRequest request = new MockHttpServletRequestBuilder(POST, "/foo")
.contentType(contentType).content(body.getBytes(UTF_8))
.buildRequest(this.servletContext);
assertThat(request.getParameterMap().get("name 1")).containsExactly("value 1");
@ -414,7 +416,7 @@ class MockHttpServletRequestBuilderTests {
@Test
void body() throws IOException {
byte[] body = "Hello World".getBytes(StandardCharsets.UTF_8);
byte[] body = "Hello World".getBytes(UTF_8);
this.builder.content(body);
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
@ -492,9 +494,9 @@ class MockHttpServletRequestBuilderTests {
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertThat(request.getCharacterEncoding()).isEqualTo(encoding);
this.builder.characterEncoding(StandardCharsets.ISO_8859_1);
this.builder.characterEncoding(ISO_8859_1);
request = this.builder.buildRequest(this.servletContext);
assertThat(request.getCharacterEncoding()).isEqualTo(StandardCharsets.ISO_8859_1.name());
assertThat(request.getCharacterEncoding()).isEqualTo(ISO_8859_1.name());
}
@Test
@ -563,7 +565,7 @@ class MockHttpServletRequestBuilderTests {
final String EXPECTED = "override";
MockHttpServletRequestBuilder defaultBuilder =
new MockHttpServletRequestBuilder(HttpMethod.GET, "/foo/bar")
new MockHttpServletRequestBuilder(GET, "/foo/bar")
.with(requestAttr(ATTR).value("default"))
.with(requestAttr(ATTR).value(EXPECTED));

View File

@ -16,94 +16,93 @@
package org.springframework.test.web.servlet.result;
import java.nio.charset.StandardCharsets;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.StubMvcResult;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
/**
* @author Rossen Stoyanchev
* @author Sebastien Deleuze
*/
public class ContentResultMatchersTests {
class ContentResultMatchersTests {
@Test
public void typeMatches() throws Exception {
new ContentResultMatchers().contentType(MediaType.APPLICATION_JSON_VALUE).match(getStubMvcResult(CONTENT));
void typeMatches() throws Exception {
new ContentResultMatchers().contentType(APPLICATION_JSON_VALUE).match(getStubMvcResult(CONTENT));
}
@Test
public void typeNoMatch() throws Exception {
void typeNoMatch() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new ContentResultMatchers().contentType("text/plain").match(getStubMvcResult(CONTENT)));
}
@Test
public void string() throws Exception {
new ContentResultMatchers().string(new String(CONTENT.getBytes(StandardCharsets.UTF_8))).match(getStubMvcResult(CONTENT));
void string() throws Exception {
new ContentResultMatchers().string(new String(CONTENT.getBytes(UTF_8))).match(getStubMvcResult(CONTENT));
}
@Test
public void stringNoMatch() throws Exception {
void stringNoMatch() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new ContentResultMatchers().encoding("bogus").match(getStubMvcResult(CONTENT)));
}
@Test
public void stringMatcher() throws Exception {
String content = new String(CONTENT.getBytes(StandardCharsets.UTF_8));
void stringMatcher() throws Exception {
String content = new String(CONTENT.getBytes(UTF_8));
new ContentResultMatchers().string(Matchers.equalTo(content)).match(getStubMvcResult(CONTENT));
}
@Test
public void stringMatcherNoMatch() throws Exception {
void stringMatcherNoMatch() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new ContentResultMatchers().string(Matchers.equalTo("bogus")).match(getStubMvcResult(CONTENT)));
}
@Test
public void bytes() throws Exception {
new ContentResultMatchers().bytes(CONTENT.getBytes(StandardCharsets.UTF_8)).match(getStubMvcResult(CONTENT));
void bytes() throws Exception {
new ContentResultMatchers().bytes(CONTENT.getBytes(UTF_8)).match(getStubMvcResult(CONTENT));
}
@Test
public void bytesNoMatch() throws Exception {
void bytesNoMatch() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new ContentResultMatchers().bytes("bogus".getBytes()).match(getStubMvcResult(CONTENT)));
}
@Test
public void jsonLenientMatch() throws Exception {
void jsonLenientMatch() throws Exception {
new ContentResultMatchers().json("{\n \"foo\" : \"bar\" \n}").match(getStubMvcResult(CONTENT));
new ContentResultMatchers().json("{\n \"foo\" : \"bar\" \n}", false).match(getStubMvcResult(CONTENT));
}
@Test
public void jsonStrictMatch() throws Exception {
void jsonStrictMatch() throws Exception {
new ContentResultMatchers().json("{\n \"foo\":\"bar\", \"foo array\":[\"foo\",\"bar\"] \n}", true).match(getStubMvcResult(CONTENT));
new ContentResultMatchers().json("{\n \"foo array\":[\"foo\",\"bar\"], \"foo\":\"bar\" \n}", true).match(getStubMvcResult(CONTENT));
}
@Test
public void jsonLenientNoMatch() throws Exception {
void jsonLenientNoMatch() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new ContentResultMatchers().json("{\n\"fooo\":\"bar\"\n}").match(getStubMvcResult(CONTENT)));
}
@Test
public void jsonStrictNoMatch() throws Exception {
void jsonStrictNoMatch() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new ContentResultMatchers().json("{\"foo\":\"bar\", \"foo array\":[\"bar\",\"foo\"]}", true).match(getStubMvcResult(CONTENT)));
}
@Test // gh-23622
public void jsonUtf8Match() throws Exception {
void jsonUtf8Match() throws Exception {
new ContentResultMatchers().json("{\"name\":\"Jürgen\"}").match(getStubMvcResult(UTF8_CONTENT));
}
@ -113,8 +112,8 @@ public class ContentResultMatchersTests {
private StubMvcResult getStubMvcResult(String content) throws Exception {
MockHttpServletResponse response = new MockHttpServletResponse();
response.addHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE);
response.getOutputStream().write(content.getBytes(StandardCharsets.UTF_8));
response.addHeader("Content-Type", APPLICATION_JSON_VALUE);
response.getOutputStream().write(content.getBytes(UTF_8));
return new StubMvcResult(null, null, null, null, null, null, response);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2022 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.
@ -16,14 +16,14 @@
package org.springframework.test.web.servlet.result;
import java.nio.charset.StandardCharsets;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.StubMvcResult;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
@ -35,19 +35,20 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
* @author Brian Clozel
* @author Sebastien Deleuze
*/
public class JsonPathResultMatchersTests {
class JsonPathResultMatchersTests {
private static final String RESPONSE_CONTENT = "{" + //
"'str': 'foo', " + //
"'utf8Str': 'Příliš', " + //
"'num': 5, " + //
"'bool': true, " + //
"'arr': [42], " + //
"'colorMap': {'red': 'rojo'}, " + //
"'emptyString': '', " + //
"'emptyArray': [], " + //
"'emptyMap': {} " + //
"}";
private static final String RESPONSE_CONTENT = """
{
'str': 'foo',
'utf8Str': 'Příliš',
'num': 5,
'bool': true,
'arr': [42],
'colorMap': {'red': 'rojo'},
'emptyString': '',
'emptyArray': [],
'emptyMap': {}
}""";
private static final StubMvcResult stubMvcResult;
@ -55,7 +56,7 @@ public class JsonPathResultMatchersTests {
try {
MockHttpServletResponse response = new MockHttpServletResponse();
response.addHeader("Content-Type", "application/json");
response.getOutputStream().write(RESPONSE_CONTENT.getBytes(StandardCharsets.UTF_8));
response.getOutputStream().write(RESPONSE_CONTENT.getBytes(UTF_8));
stubMvcResult = new StubMvcResult(null, null, null, null, null, null, response);
}
catch (Exception e) {
@ -63,220 +64,221 @@ public class JsonPathResultMatchersTests {
}
}
@Test
public void valueWithValueMismatch() throws Exception {
void valueWithValueMismatch() throws Exception {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> new JsonPathResultMatchers("$.str").value("bogus").match(stubMvcResult))
.withMessage("JSON path \"$.str\" expected:<bogus> but was:<foo>");
}
@Test
public void valueWithTypeMismatch() throws Exception {
void valueWithTypeMismatch() throws Exception {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> new JsonPathResultMatchers("$.str").value("bogus".getBytes()).match(stubMvcResult))
.withMessage("At JSON path \"$.str\", value <foo> of type <java.lang.String> cannot be converted to type <byte[]>");
}
@Test
public void valueWithDirectMatch() throws Exception {
void valueWithDirectMatch() throws Exception {
new JsonPathResultMatchers("$.str").value("foo").match(stubMvcResult);
}
@Test // gh-23219
public void utf8ValueWithDirectMatch() throws Exception {
void utf8ValueWithDirectMatch() throws Exception {
new JsonPathResultMatchers("$.utf8Str").value("Příliš").match(stubMvcResult);
}
@Test // SPR-16587
public void valueWithNumberConversion() throws Exception {
void valueWithNumberConversion() throws Exception {
new JsonPathResultMatchers("$.num").value(5.0f).match(stubMvcResult);
}
@Test
public void valueWithMatcher() throws Exception {
void valueWithMatcher() throws Exception {
new JsonPathResultMatchers("$.str").value(Matchers.equalTo("foo")).match(stubMvcResult);
}
@Test // SPR-16587
public void valueWithMatcherAndNumberConversion() throws Exception {
void valueWithMatcherAndNumberConversion() throws Exception {
new JsonPathResultMatchers("$.num").value(Matchers.equalTo(5.0f), Float.class).match(stubMvcResult);
}
@Test
public void valueWithMatcherAndMismatch() throws Exception {
void valueWithMatcherAndMismatch() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.str").value(Matchers.equalTo("bogus")).match(stubMvcResult));
}
@Test
public void exists() throws Exception {
void exists() throws Exception {
new JsonPathResultMatchers("$.str").exists().match(stubMvcResult);
}
@Test
public void existsForAnEmptyArray() throws Exception {
void existsForAnEmptyArray() throws Exception {
new JsonPathResultMatchers("$.emptyArray").exists().match(stubMvcResult);
}
@Test
public void existsForAnEmptyMap() throws Exception {
void existsForAnEmptyMap() throws Exception {
new JsonPathResultMatchers("$.emptyMap").exists().match(stubMvcResult);
}
@Test
public void existsNoMatch() throws Exception {
void existsNoMatch() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.bogus").exists().match(stubMvcResult));
}
@Test
public void doesNotExist() throws Exception {
void doesNotExist() throws Exception {
new JsonPathResultMatchers("$.bogus").doesNotExist().match(stubMvcResult);
}
@Test
public void doesNotExistNoMatch() throws Exception {
void doesNotExistNoMatch() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.str").doesNotExist().match(stubMvcResult));
}
@Test
public void doesNotExistForAnEmptyArray() throws Exception {
void doesNotExistForAnEmptyArray() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.emptyArray").doesNotExist().match(stubMvcResult));
}
@Test
public void doesNotExistForAnEmptyMap() throws Exception {
void doesNotExistForAnEmptyMap() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.emptyMap").doesNotExist().match(stubMvcResult));
}
@Test
public void isEmptyForAnEmptyString() throws Exception {
void isEmptyForAnEmptyString() throws Exception {
new JsonPathResultMatchers("$.emptyString").isEmpty().match(stubMvcResult);
}
@Test
public void isEmptyForAnEmptyArray() throws Exception {
void isEmptyForAnEmptyArray() throws Exception {
new JsonPathResultMatchers("$.emptyArray").isEmpty().match(stubMvcResult);
}
@Test
public void isEmptyForAnEmptyMap() throws Exception {
void isEmptyForAnEmptyMap() throws Exception {
new JsonPathResultMatchers("$.emptyMap").isEmpty().match(stubMvcResult);
}
@Test
public void isNotEmptyForString() throws Exception {
void isNotEmptyForString() throws Exception {
new JsonPathResultMatchers("$.str").isNotEmpty().match(stubMvcResult);
}
@Test
public void isNotEmptyForNumber() throws Exception {
void isNotEmptyForNumber() throws Exception {
new JsonPathResultMatchers("$.num").isNotEmpty().match(stubMvcResult);
}
@Test
public void isNotEmptyForBoolean() throws Exception {
void isNotEmptyForBoolean() throws Exception {
new JsonPathResultMatchers("$.bool").isNotEmpty().match(stubMvcResult);
}
@Test
public void isNotEmptyForArray() throws Exception {
void isNotEmptyForArray() throws Exception {
new JsonPathResultMatchers("$.arr").isNotEmpty().match(stubMvcResult);
}
@Test
public void isNotEmptyForMap() throws Exception {
void isNotEmptyForMap() throws Exception {
new JsonPathResultMatchers("$.colorMap").isNotEmpty().match(stubMvcResult);
}
@Test
public void isNotEmptyForAnEmptyString() throws Exception {
void isNotEmptyForAnEmptyString() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.emptyString").isNotEmpty().match(stubMvcResult));
}
@Test
public void isNotEmptyForAnEmptyArray() throws Exception {
void isNotEmptyForAnEmptyArray() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.emptyArray").isNotEmpty().match(stubMvcResult));
}
@Test
public void isNotEmptyForAnEmptyMap() throws Exception {
void isNotEmptyForAnEmptyMap() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.emptyMap").isNotEmpty().match(stubMvcResult));
}
@Test
public void isArray() throws Exception {
void isArray() throws Exception {
new JsonPathResultMatchers("$.arr").isArray().match(stubMvcResult);
}
@Test
public void isArrayForAnEmptyArray() throws Exception {
void isArrayForAnEmptyArray() throws Exception {
new JsonPathResultMatchers("$.emptyArray").isArray().match(stubMvcResult);
}
@Test
public void isArrayNoMatch() throws Exception {
void isArrayNoMatch() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.bar").isArray().match(stubMvcResult));
}
@Test
public void isMap() throws Exception {
void isMap() throws Exception {
new JsonPathResultMatchers("$.colorMap").isMap().match(stubMvcResult);
}
@Test
public void isMapForAnEmptyMap() throws Exception {
void isMapForAnEmptyMap() throws Exception {
new JsonPathResultMatchers("$.emptyMap").isMap().match(stubMvcResult);
}
@Test
public void isMapNoMatch() throws Exception {
void isMapNoMatch() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.str").isMap().match(stubMvcResult));
}
@Test
public void isBoolean() throws Exception {
void isBoolean() throws Exception {
new JsonPathResultMatchers("$.bool").isBoolean().match(stubMvcResult);
}
@Test
public void isBooleanNoMatch() throws Exception {
void isBooleanNoMatch() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.str").isBoolean().match(stubMvcResult));
}
@Test
public void isNumber() throws Exception {
void isNumber() throws Exception {
new JsonPathResultMatchers("$.num").isNumber().match(stubMvcResult);
}
@Test
public void isNumberNoMatch() throws Exception {
void isNumberNoMatch() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.str").isNumber().match(stubMvcResult));
}
@Test
public void isString() throws Exception {
void isString() throws Exception {
new JsonPathResultMatchers("$.str").isString().match(stubMvcResult);
}
@Test
public void isStringNoMatch() throws Exception {
void isStringNoMatch() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.arr").isString().match(stubMvcResult));
}
@Test
public void valueWithJsonPrefixNotConfigured() throws Exception {
void valueWithJsonPrefixNotConfigured() throws Exception {
String jsonPrefix = "prefix";
StubMvcResult result = createPrefixedStubMvcResult(jsonPrefix);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
@ -284,7 +286,7 @@ public class JsonPathResultMatchersTests {
}
@Test
public void valueWithJsonWrongPrefix() throws Exception {
void valueWithJsonWrongPrefix() throws Exception {
String jsonPrefix = "prefix";
StubMvcResult result = createPrefixedStubMvcResult(jsonPrefix);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
@ -292,17 +294,17 @@ public class JsonPathResultMatchersTests {
}
@Test
public void valueWithJsonPrefix() throws Exception {
void valueWithJsonPrefix() throws Exception {
String jsonPrefix = "prefix";
StubMvcResult result = createPrefixedStubMvcResult(jsonPrefix);
new JsonPathResultMatchers("$.str").prefix(jsonPrefix).value("foo").match(result);
}
@Test
public void prefixWithPayloadNotLongEnough() throws Exception {
void prefixWithPayloadNotLongEnough() throws Exception {
MockHttpServletResponse response = new MockHttpServletResponse();
response.addHeader("Content-Type", "application/json");
response.getWriter().print(new String("test".getBytes(StandardCharsets.ISO_8859_1)));
response.getWriter().print(new String("test".getBytes(ISO_8859_1)));
StubMvcResult result = new StubMvcResult(null, null, null, null, null, null, response);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
@ -312,7 +314,7 @@ public class JsonPathResultMatchersTests {
private StubMvcResult createPrefixedStubMvcResult(String jsonPrefix) throws Exception {
MockHttpServletResponse response = new MockHttpServletResponse();
response.addHeader("Content-Type", "application/json");
response.getWriter().print(jsonPrefix + new String(RESPONSE_CONTENT.getBytes(StandardCharsets.ISO_8859_1)));
response.getWriter().print(jsonPrefix + new String(RESPONSE_CONTENT.getBytes(ISO_8859_1)));
return new StubMvcResult(null, null, null, null, null, null, response);
}

View File

@ -17,7 +17,6 @@
package org.springframework.test.web.servlet.result;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@ -43,6 +42,8 @@ import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.FlashMap;
import org.springframework.web.servlet.ModelAndView;
import static java.nio.charset.StandardCharsets.UTF_16;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
/**
@ -52,7 +53,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Sam Brannen
* @see org.springframework.test.web.servlet.samples.standalone.resulthandlers.PrintingResultHandlerSmokeTests
*/
public class PrintingResultHandlerTests {
class PrintingResultHandlerTests {
private final TestPrintingResultHandler handler = new TestPrintingResultHandler();
@ -70,12 +71,12 @@ public class PrintingResultHandlerTests {
@Test
public void printRequest() throws Exception {
void printRequest() throws Exception {
this.request.addParameter("param", "paramValue");
this.request.addHeader("header", "headerValue");
this.request.setCharacterEncoding("UTF-16");
String palindrome = "ablE was I ere I saw Elba";
byte[] bytes = palindrome.getBytes(StandardCharsets.UTF_16);
byte[] bytes = palindrome.getBytes(UTF_16);
this.request.setContent(bytes);
this.request.getSession().setAttribute("foo", "bar");
@ -96,12 +97,12 @@ public class PrintingResultHandlerTests {
}
@Test
public void printRequestWithoutSession() throws Exception {
void printRequestWithoutSession() throws Exception {
this.request.addParameter("param", "paramValue");
this.request.addHeader("header", "headerValue");
this.request.setCharacterEncoding("UTF-16");
String palindrome = "ablE was I ere I saw Elba";
byte[] bytes = palindrome.getBytes(StandardCharsets.UTF_16);
byte[] bytes = palindrome.getBytes(UTF_16);
this.request.setContent(bytes);
this.handler.handle(this.mvcResult);
@ -120,12 +121,12 @@ public class PrintingResultHandlerTests {
}
@Test
public void printRequestWithEmptySessionMock() throws Exception {
void printRequestWithEmptySessionMock() throws Exception {
this.request.addParameter("param", "paramValue");
this.request.addHeader("header", "headerValue");
this.request.setCharacterEncoding("UTF-16");
String palindrome = "ablE was I ere I saw Elba";
byte[] bytes = palindrome.getBytes(StandardCharsets.UTF_16);
byte[] bytes = palindrome.getBytes(UTF_16);
this.request.setContent(bytes);
this.request.setSession(Mockito.mock(HttpSession.class));
@ -146,7 +147,7 @@ public class PrintingResultHandlerTests {
@Test
@SuppressWarnings("removal")
public void printResponse() throws Exception {
void printResponse() throws Exception {
Cookie enigmaCookie = new Cookie("enigma", "42");
enigmaCookie.setHttpOnly(true);
enigmaCookie.setMaxAge(1234);
@ -203,9 +204,9 @@ public class PrintingResultHandlerTests {
}
@Test
public void printRequestWithCharacterEncoding() throws Exception {
void printRequestWithCharacterEncoding() throws Exception {
this.request.setCharacterEncoding("UTF-8");
this.request.setContent("text".getBytes(StandardCharsets.UTF_8));
this.request.setContent("text".getBytes(UTF_8));
this.handler.handle(this.mvcResult);
@ -213,14 +214,14 @@ public class PrintingResultHandlerTests {
}
@Test
public void printRequestWithoutCharacterEncoding() throws Exception {
void printRequestWithoutCharacterEncoding() throws Exception {
this.handler.handle(this.mvcResult);
assertValue("MockHttpServletRequest", "Body", "<no character encoding set>");
}
@Test
public void printResponseWithCharacterEncoding() throws Exception {
void printResponseWithCharacterEncoding() throws Exception {
this.response.setCharacterEncoding("UTF-8");
this.response.getWriter().print("text");
@ -229,7 +230,7 @@ public class PrintingResultHandlerTests {
}
@Test
public void printResponseWithDefaultCharacterEncoding() throws Exception {
void printResponseWithDefaultCharacterEncoding() throws Exception {
this.response.getWriter().print("text");
this.handler.handle(this.mvcResult);
@ -238,7 +239,7 @@ public class PrintingResultHandlerTests {
}
@Test
public void printHandlerNull() throws Exception {
void printHandlerNull() throws Exception {
StubMvcResult mvcResult = new StubMvcResult(this.request, null, null, null, null, null, this.response);
this.handler.handle(mvcResult);
@ -246,7 +247,7 @@ public class PrintingResultHandlerTests {
}
@Test
public void printHandler() throws Exception {
void printHandler() throws Exception {
this.mvcResult.setHandler(new Object());
this.handler.handle(this.mvcResult);
@ -254,7 +255,7 @@ public class PrintingResultHandlerTests {
}
@Test
public void printHandlerMethod() throws Exception {
void printHandlerMethod() throws Exception {
HandlerMethod handlerMethod = new HandlerMethod(this, "handle");
this.mvcResult.setHandler(handlerMethod);
this.handler.handle(mvcResult);
@ -264,14 +265,14 @@ public class PrintingResultHandlerTests {
}
@Test
public void resolvedExceptionNull() throws Exception {
void resolvedExceptionNull() throws Exception {
this.handler.handle(this.mvcResult);
assertValue("Resolved Exception", "Type", null);
}
@Test
public void resolvedException() throws Exception {
void resolvedException() throws Exception {
this.mvcResult.setResolvedException(new Exception());
this.handler.handle(this.mvcResult);
@ -279,7 +280,7 @@ public class PrintingResultHandlerTests {
}
@Test
public void modelAndViewNull() throws Exception {
void modelAndViewNull() throws Exception {
this.handler.handle(this.mvcResult);
assertValue("ModelAndView", "View name", null);
@ -288,7 +289,7 @@ public class PrintingResultHandlerTests {
}
@Test
public void modelAndView() throws Exception {
void modelAndView() throws Exception {
BindException bindException = new BindException(new Object(), "target");
bindException.reject("errorCode");
@ -307,14 +308,14 @@ public class PrintingResultHandlerTests {
}
@Test
public void flashMapNull() throws Exception {
void flashMapNull() throws Exception {
this.handler.handle(mvcResult);
assertValue("FlashMap", "Type", null);
}
@Test
public void flashMap() throws Exception {
void flashMap() throws Exception {
FlashMap flashMap = new FlashMap();
flashMap.put("attrName", "attrValue");
this.request.setAttribute(DispatcherServlet.class.getName() + ".OUTPUT_FLASH_MAP", flashMap);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 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.

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2022 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.

View File

@ -16,8 +16,6 @@
package org.springframework.test.web.servlet.samples.client.standalone.resultmatches;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
@ -27,8 +25,11 @@ import org.springframework.test.web.servlet.client.MockMvcWebTestClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.http.MediaType.TEXT_PLAIN;
/**
* {@link MockMvcWebTestClient} equivalent of the MockMvc
@ -36,20 +37,20 @@ import static org.hamcrest.Matchers.equalTo;
*
* @author Rossen Stoyanchev
*/
public class ContentAssertionTests {
class ContentAssertionTests {
private final WebTestClient testClient =
MockMvcWebTestClient.bindToController(new SimpleController()).build();
@Test
public void testContentType() {
testClient.get().uri("/handle").accept(MediaType.TEXT_PLAIN)
void contentType() {
testClient.get().uri("/handle").accept(TEXT_PLAIN)
.exchange()
.expectStatus().isOk()
.expectHeader().contentType(MediaType.valueOf("text/plain;charset=ISO-8859-1"))
.expectHeader().contentType("text/plain;charset=ISO-8859-1")
.expectHeader().contentTypeCompatibleWith("text/plain")
.expectHeader().contentTypeCompatibleWith(MediaType.TEXT_PLAIN);
.expectHeader().contentTypeCompatibleWith(TEXT_PLAIN);
testClient.get().uri("/handleUtf8")
.exchange()
@ -57,24 +58,23 @@ public class ContentAssertionTests {
.expectHeader().contentType(MediaType.valueOf("text/plain;charset=UTF-8"))
.expectHeader().contentType("text/plain;charset=UTF-8")
.expectHeader().contentTypeCompatibleWith("text/plain")
.expectHeader().contentTypeCompatibleWith(MediaType.TEXT_PLAIN);
.expectHeader().contentTypeCompatibleWith(TEXT_PLAIN);
}
@Test
public void testContentAsString() {
testClient.get().uri("/handle").accept(MediaType.TEXT_PLAIN)
void contentAsString() {
testClient.get().uri("/handle").accept(TEXT_PLAIN)
.exchange()
.expectStatus().isOk()
.expectBody(String.class).isEqualTo("Hello world!");
testClient.get().uri("/handleUtf8").accept(MediaType.TEXT_PLAIN)
testClient.get().uri("/handleUtf8").accept(TEXT_PLAIN)
.exchange()
.expectStatus().isOk()
.expectBody(String.class).isEqualTo("\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01");
// Hamcrest matchers...
testClient.get().uri("/handle").accept(MediaType.TEXT_PLAIN)
testClient.get().uri("/handle").accept(TEXT_PLAIN)
.exchange()
.expectStatus().isOk()
.expectBody(String.class).value(equalTo("Hello world!"));
@ -85,33 +85,31 @@ public class ContentAssertionTests {
}
@Test
public void testContentAsBytes() {
testClient.get().uri("/handle").accept(MediaType.TEXT_PLAIN)
void contentAsBytes() {
testClient.get().uri("/handle").accept(TEXT_PLAIN)
.exchange()
.expectStatus().isOk()
.expectBody(byte[].class).isEqualTo(
"Hello world!".getBytes(StandardCharsets.ISO_8859_1));
"Hello world!".getBytes(ISO_8859_1));
testClient.get().uri("/handleUtf8")
.exchange()
.expectStatus().isOk()
.expectBody(byte[].class).isEqualTo(
"\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01".getBytes(StandardCharsets.UTF_8));
"\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01".getBytes(UTF_8));
}
@Test
public void testContentStringMatcher() {
testClient.get().uri("/handle").accept(MediaType.TEXT_PLAIN)
void contentStringMatcher() {
testClient.get().uri("/handle").accept(TEXT_PLAIN)
.exchange()
.expectStatus().isOk()
.expectBody(String.class).value(containsString("world"));
}
@Test
public void testCharacterEncoding() {
testClient.get().uri("/handle").accept(MediaType.TEXT_PLAIN)
void characterEncoding() {
testClient.get().uri("/handle").accept(TEXT_PLAIN)
.exchange()
.expectStatus().isOk()
.expectHeader().contentType("text/plain;charset=ISO-8859-1")
@ -122,22 +120,22 @@ public class ContentAssertionTests {
.expectStatus().isOk()
.expectHeader().contentType("text/plain;charset=UTF-8")
.expectBody(byte[].class)
.isEqualTo("\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01".getBytes(StandardCharsets.UTF_8));
.isEqualTo("\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01".getBytes(UTF_8));
}
@Controller
private static class SimpleController {
@RequestMapping(value="/handle", produces="text/plain")
@RequestMapping(path="/handle", produces="text/plain")
@ResponseBody
public String handle() {
String handle() {
return "Hello world!";
}
@RequestMapping(value="/handleUtf8", produces="text/plain;charset=UTF-8")
@RequestMapping(path="/handleUtf8", produces="text/plain;charset=UTF-8")
@ResponseBody
public String handleWithCharset() {
String handleWithCharset() {
return "\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01"; // "Hello world! (Japanese)
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2022 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.

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2022 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.

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2022 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.

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 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.
@ -155,13 +155,9 @@ public class XpathAssertionTests {
.andExpect(xpath("/ns:people/performers/performer", musicNamespace).nodeCount(equalTo(2)));
}
// SPR-10704
@Test
@Test // SPR-10704
public void testFeedWithLinefeedChars() throws Exception {
// Map<String, String> namespace = Collections.singletonMap("ns", "");
standaloneSetup(new BlogFeedController()).build()
.perform(get("/blog.atom").accept(MediaType.APPLICATION_ATOM_XML))
.andExpect(status().isOk())