From 2f9933e3cb7532eda9f948d94354fecf09122d2e Mon Sep 17 00:00:00 2001 From: Brian Clozel Date: Mon, 27 Jul 2026 16:09:12 +0200 Subject: [PATCH] Replace TestRestTemplate with RestTestClient in smoke tests Before deprecating `TestRestTemplate`, we must first stop using it in smoke tests and replace it with: * `RestTestClient` when the Spring MVC infrastructure is present * `RestClient` when the test does not have Spring MVC on classpath See gh-46632 --- ...ractSampleActuatorCustomSecurityTests.java | 184 ++++++++------- .../CorsSampleActuatorApplicationTests.java | 58 ++--- ...asePathSampleActuatorApplicationTests.java | 18 +- ...asePathSampleActuatorApplicationTests.java | 18 +- ...hCustomServletPathSampleActuatorTests.java | 16 +- ...ctuatorCustomSecurityApplicationTests.java | 21 +- ...mpleActuatorExtensionApplicationTests.java | 43 +--- .../SampleActuatorUiApplicationPortTests.java | 48 ++-- .../ui/SampleActuatorUiApplicationTests.java | 60 +++-- ...AndPathSampleActuatorApplicationTests.java | 96 +++++--- .../CorsSampleActuatorApplicationTests.java | 58 ++--- ...pertiesSampleActuatorApplicationTests.java | 45 ++-- ...gementAddressActuatorApplicationTests.java | 35 +-- ...HandlerSampleActuatorApplicationTests.java | 20 +- ...entPortSampleActuatorApplicationTests.java | 17 +- ...entPathSampleActuatorApplicationTests.java | 39 ++-- ...entPortSampleActuatorApplicationTests.java | 80 ++++--- ...gementPortWithLazyInitializationTests.java | 17 +- ...redPortSampleActuatorApplicationTests.java | 17 +- ...agementSampleActuatorApplicationTests.java | 35 ++- ...plicationIsolatedJsonMapperFalseTests.java | 22 +- ...pplicationIsolatedJsonMapperTrueTests.java | 20 +- .../SampleActuatorApplicationTests.java | 215 ++++++++++-------- ...letPathSampleActuatorApplicationTests.java | 53 +++-- ...hutdownSampleActuatorApplicationTests.java | 40 ++-- ...leDevToolsApplicationIntegrationTests.java | 29 +-- .../SampleHateoasApplicationTests.java | 53 ++--- .../AbstractJerseyApplicationTests.java | 25 +- .../AbstractJerseyManagementPortTests.java | 28 ++- ...ctuatorIsolatedObjectMapperFalseTests.java | 18 +- ...ActuatorIsolatedObjectMapperTrueTests.java | 15 +- ...ApplicationPathAndManagementPortTests.java | 15 +- ...entPortSampleActuatorApplicationTests.java | 10 +- .../jsp/SampleWebJspApplicationTests.java | 18 +- .../build.gradle | 2 +- .../ssl/SampleJettySslApplicationTests.java | 19 +- .../jetty/SampleJettyApplicationTests.java | 40 ++-- ...h2AuthorizationServerApplicationTests.java | 113 ++++----- .../SampleOAuth2ClientApplicationTests.java | 43 ++-- ...eOauth2ResourceServerApplicationTests.java | 30 +-- .../SamplePrometheusApplicationTests.java | 24 +- .../SampleQuartzApplicationWebTests.java | 92 ++++---- ...mpleSaml2RelyingPartyApplicationTests.java | 39 ++-- .../jersey/AbstractJerseySecureTests.java | 88 ++++--- ...mentPortAndPathJerseyApplicationTests.java | 5 +- ...tPortCustomApplicationPathJerseyTests.java | 5 +- .../build.gradle | 1 - .../SampleServletApplicationTests.java | 37 +-- .../SampleSessionRedisApplicationTests.java | 48 ++-- .../SampleSessionJdbcApplicationTests.java | 56 +++-- ...pleTestApplicationWebIntegrationTests.java | 13 +- .../testng/SampleTestNGApplicationTests.java | 16 +- .../jsp/SampleWebJspApplicationTests.java | 18 +- .../build.gradle | 2 +- ...leTomcatTwoConnectorsApplicationTests.java | 26 +-- .../build.gradle | 2 +- .../ssl/SampleTomcatSslApplicationTests.java | 40 ++-- ...igurationSampleTomcatApplicationTests.java | 16 +- .../tomcat/SampleTomcatApplicationTests.java | 81 ++++--- .../SampleTraditionalApplicationTests.java | 28 +-- .../SampleWebFreeMarkerApplicationTests.java | 56 ++--- .../SampleGroovyTemplateApplicationTests.java | 37 +-- .../jsp/SampleWebJspApplicationTests.java | 37 ++- .../SampleMethodSecurityApplicationTests.java | 108 +++++---- .../SampleWebMustacheApplicationTests.java | 82 +++---- ...SampleWebSecureCustomApplicationTests.java | 65 +++--- .../SampleWebSecureJdbcApplicationTests.java | 65 +++--- .../web/secure/AbstractErrorPageTests.java | 94 ++++---- ...AbstractUnauthenticatedErrorPageTests.java | 121 ++++++---- .../SampleWebSecureApplicationTests.java | 65 +++--- .../SampleWebStaticApplicationTests.java | 30 +-- .../SampleWebUiApplicationTests.java | 26 ++- ...ApplicationActuatorDifferentPortTests.java | 19 +- 73 files changed, 1646 insertions(+), 1529 deletions(-) diff --git a/smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/AbstractSampleActuatorCustomSecurityTests.java b/smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/AbstractSampleActuatorCustomSecurityTests.java index 6d66018bcb6..aa3a2fecf69 100644 --- a/smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/AbstractSampleActuatorCustomSecurityTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/AbstractSampleActuatorCustomSecurityTests.java @@ -16,15 +16,12 @@ package smoketest.actuator.customsecurity; -import java.util.Map; - import org.junit.jupiter.api.Test; -import org.springframework.boot.resttestclient.TestRestTemplate; import org.springframework.boot.test.http.server.LocalTestWebServer; import org.springframework.context.ApplicationContext; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -43,156 +40,177 @@ abstract class AbstractSampleActuatorCustomSecurityTests { @Test void homeIsSecure() { - @SuppressWarnings("rawtypes") - ResponseEntity entity = restTemplate().getForEntity(getPath() + "/", Map.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); - assertThat(entity.getHeaders().headerNames()).doesNotContain("Set-Cookie"); + restTestClient().get() + .uri(getPath() + "/") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isUnauthorized() + .expectHeader() + .doesNotExist("Set-Cookie"); } @Test void testInsecureStaticResources() { - ResponseEntity entity = restTemplate().getForEntity(getPath() + "/css/bootstrap.min.css", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("body"); + restTestClient().get() + .uri(getPath() + "/css/bootstrap.min.css") + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("body")); } @Test void actuatorInsecureEndpoint() { - ResponseEntity entity = restTemplate().getForEntity(getActuatorPath() + "/health", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("\"status\":\"UP\""); - entity = restTemplate().getForEntity(getActuatorPath() + "/health/diskSpace", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("\"status\":\"UP\""); + RestTestClient restTestClient = restTestClient(); + restTestClient.get() + .uri(getActuatorPath() + "/health") + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("\"status\":\"UP\"")); + restTestClient.get() + .uri(getActuatorPath() + "/health/diskSpace") + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("\"status\":\"UP\"")); } @Test void actuatorLinksWithAnonymous() { - ResponseEntity entity = restTemplate().getForEntity(getActuatorPath(), Object.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); - entity = restTemplate().getForEntity(getActuatorPath() + "/", Object.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + RestTestClient restTestClient = restTestClient(); + restTestClient.get().uri(getActuatorPath()).exchange().expectStatus().isUnauthorized(); + restTestClient.get().uri(getActuatorPath() + "/").exchange().expectStatus().isUnauthorized(); } @Test void actuatorLinksWithUnauthorizedUser() { - ResponseEntity entity = userRestTemplate().getForEntity(getActuatorPath(), Object.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); - entity = userRestTemplate().getForEntity(getActuatorPath() + "/", Object.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); + RestTestClient restTestClient = userRestTestClient(); + restTestClient.get().uri(getActuatorPath()).exchange().expectStatus().isForbidden(); + restTestClient.get().uri(getActuatorPath() + "/").exchange().expectStatus().isForbidden(); } @Test void actuatorLinksWithAuthorizedUser() { - ResponseEntity entity = adminRestTemplate().getForEntity(getActuatorPath(), Object.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - adminRestTemplate().getForEntity(getActuatorPath() + "/", Object.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + RestTestClient restTestClient = adminRestTestClient(); + restTestClient.get().uri(getActuatorPath()).accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk(); } @Test void actuatorSecureEndpointWithAnonymous() { - ResponseEntity entity = restTemplate().getForEntity(getActuatorPath() + "/env", Object.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); - entity = restTemplate().getForEntity(getActuatorPath() + "/env/management.endpoints.web.exposure.include", - Object.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + RestTestClient restTestClient = restTestClient(); + restTestClient.get().uri(getActuatorPath() + "/env").exchange().expectStatus().isUnauthorized(); + restTestClient.get() + .uri(getActuatorPath() + "/env/management.endpoints.web.exposure.include") + .exchange() + .expectStatus() + .isUnauthorized(); } @Test void actuatorSecureEndpointWithUnauthorizedUser() { - ResponseEntity entity = userRestTemplate().getForEntity(getActuatorPath() + "/env", Object.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); - entity = userRestTemplate().getForEntity(getActuatorPath() + "/env/management.endpoints.web.exposure.include", - Object.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); + RestTestClient restTestClient = userRestTestClient(); + restTestClient.get().uri(getActuatorPath() + "/env").exchange().expectStatus().isForbidden(); + restTestClient.get() + .uri(getActuatorPath() + "/env/management.endpoints.web.exposure.include") + .exchange() + .expectStatus() + .isForbidden(); } @Test void actuatorSecureEndpointWithAuthorizedUser() { - ResponseEntity entity = adminRestTemplate().getForEntity(getActuatorPath() + "/env", Object.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - entity = adminRestTemplate().getForEntity(getActuatorPath() + "/env/", Object.class); + RestTestClient restTestClient = adminRestTestClient(); + restTestClient.get().uri(getActuatorPath() + "/env").exchange().expectStatus().isOk(); // EndpointRequest matches the trailing slash but MVC doesn't - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); - entity = adminRestTemplate().getForEntity(getActuatorPath() + "/env/management.endpoints.web.exposure.include", - Object.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + restTestClient.get().uri(getActuatorPath() + "/env/").exchange().expectStatus().isNotFound(); + restTestClient.get() + .uri(getActuatorPath() + "/env/management.endpoints.web.exposure.include") + .exchange() + .expectStatus() + .isOk(); } @Test void secureServletEndpointWithAnonymous() { - ResponseEntity entity = restTemplate().getForEntity(getActuatorPath() + "/se1", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); - entity = restTemplate().getForEntity(getActuatorPath() + "/se1/list", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + RestTestClient restTestClient = restTestClient(); + restTestClient.get().uri(getActuatorPath() + "/se1").exchange().expectStatus().isUnauthorized(); + restTestClient.get().uri(getActuatorPath() + "/se1/list").exchange().expectStatus().isUnauthorized(); } @Test void secureServletEndpointWithUnauthorizedUser() { - ResponseEntity entity = userRestTemplate().getForEntity(getActuatorPath() + "/se1", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); - entity = userRestTemplate().getForEntity(getActuatorPath() + "/se1/list", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); + RestTestClient restTestClient = userRestTestClient(); + restTestClient.get().uri(getActuatorPath() + "/se1").exchange().expectStatus().isForbidden(); + restTestClient.get().uri(getActuatorPath() + "/se1/list").exchange().expectStatus().isForbidden(); } @Test void secureServletEndpointWithAuthorizedUser() { - ResponseEntity entity = adminRestTemplate().getForEntity(getActuatorPath() + "/se1", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - entity = adminRestTemplate().getForEntity(getActuatorPath() + "/se1/list", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + RestTestClient restTestClient = adminRestTestClient(); + restTestClient.get().uri(getActuatorPath() + "/se1").exchange().expectStatus().isOk(); + restTestClient.get().uri(getActuatorPath() + "/se1/list").exchange().expectStatus().isOk(); } @Test void actuatorCustomMvcSecureEndpointWithAnonymous() { - ResponseEntity entity = restTemplate().getForEntity(getActuatorPath() + "/example/echo?text={t}", - String.class, "test"); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + restTestClient().get() + .uri(getActuatorPath() + "/example/echo?text={t}", "test") + .exchange() + .expectStatus() + .isUnauthorized(); } @Test void actuatorCustomMvcSecureEndpointWithUnauthorizedUser() { - ResponseEntity entity = userRestTemplate().getForEntity(getActuatorPath() + "/example/echo?text={t}", - String.class, "test"); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); + userRestTestClient().get() + .uri(getActuatorPath() + "/example/echo?text={t}", "test") + .exchange() + .expectStatus() + .isForbidden(); } @Test void actuatorCustomMvcSecureEndpointWithAuthorizedUser() { - ResponseEntity entity = adminRestTemplate().getForEntity(getActuatorPath() + "/example/echo?text={t}", - String.class, "test"); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).isEqualTo("test"); - assertThat(entity.getHeaders().getFirst("echo")).isEqualTo("test"); + adminRestTestClient().get() + .uri(getActuatorPath() + "/example/echo?text={t}", "test") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueEquals("echo", "test") + .expectBody(String.class) + .isEqualTo("test"); } @Test void actuatorExcludedFromEndpointRequestMatcher() { - ResponseEntity entity = userRestTemplate().getForEntity(getActuatorPath() + "/mappings", Object.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + userRestTestClient().get().uri(getActuatorPath() + "/mappings").exchange().expectStatus().isOk(); } - TestRestTemplate restTemplate() { - return configure(new TestRestTemplate()); + RestTestClient restTestClient() { + return configure(RestTestClient.bindToServer()).build(); } - TestRestTemplate adminRestTemplate() { - return configure(new TestRestTemplate("admin", "admin")); + RestTestClient adminRestTestClient() { + return configure( + RestTestClient.bindToServer().defaultHeaders((headers) -> headers.setBasicAuth("admin", "admin"))) + .build(); } - TestRestTemplate userRestTemplate() { - return configure(new TestRestTemplate("user", "password")); + RestTestClient userRestTestClient() { + return configure( + RestTestClient.bindToServer().defaultHeaders((headers) -> headers.setBasicAuth("user", "password"))) + .build(); } - TestRestTemplate beansRestTemplate() { - return configure(new TestRestTemplate("beans", "beans")); + RestTestClient beansRestTestClient() { + return configure( + RestTestClient.bindToServer().defaultHeaders((headers) -> headers.setBasicAuth("beans", "beans"))) + .build(); } - private TestRestTemplate configure(TestRestTemplate restTemplate) { + RestTestClient.Builder configure(RestTestClient.Builder builder) { LocalTestWebServer localTestWebServer = LocalTestWebServer.obtain(getApplicationContext()); - restTemplate.setUriTemplateHandler(localTestWebServer.uriBuilderFactory()); - return restTemplate; + return builder.baseUrl(localTestWebServer.uri()); } } diff --git a/smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/CorsSampleActuatorApplicationTests.java b/smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/CorsSampleActuatorApplicationTests.java index 456f7e2c592..a860aa55388 100644 --- a/smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/CorsSampleActuatorApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/CorsSampleActuatorApplicationTests.java @@ -16,25 +16,13 @@ package smoketest.actuator.customsecurity; -import java.net.URI; -import java.util.Map; - -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.restclient.RestTemplateBuilder; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.http.server.LocalTestWebServer; -import org.springframework.context.ApplicationContext; -import org.springframework.http.HttpStatus; -import org.springframework.http.RequestEntity; -import org.springframework.http.ResponseEntity; import org.springframework.test.context.ActiveProfiles; - -import static org.assertj.core.api.Assertions.assertThat; +import org.springframework.test.web.servlet.client.RestTestClient; /** * Integration test for cors preflight requests to management endpoints. @@ -43,47 +31,31 @@ import static org.assertj.core.api.Assertions.assertThat; */ @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("cors") -@AutoConfigureTestRestTemplate -@SuppressWarnings("removal") +@AutoConfigureRestTestClient class CorsSampleActuatorApplicationTests { - private TestRestTemplate testRestTemplate; - @Autowired - private ApplicationContext applicationContext; - - @BeforeEach - void setUp() { - RestTemplateBuilder builder = new RestTemplateBuilder(); - LocalTestWebServer localTestWebServer = LocalTestWebServer.obtain(this.applicationContext); - builder = builder.uriTemplateHandler(localTestWebServer.uriBuilderFactory()); - this.testRestTemplate = new TestRestTemplate(builder); - } + private RestTestClient restTestClient; @Test void endpointShouldReturnUnauthorized() { - ResponseEntity entity = this.testRestTemplate.getForEntity("/actuator/env", Map.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + this.restTestClient.get().uri("/actuator/env").exchange().expectStatus().isUnauthorized(); } @Test - void preflightRequestToEndpointShouldReturnOk() throws Exception { - RequestEntity envRequest = RequestEntity.options(new URI("/actuator/env")) - .header("Origin", "http://localhost:8080") - .header("Access-Control-Request-Method", "GET") - .build(); - ResponseEntity exchange = this.testRestTemplate.exchange(envRequest, Map.class); - assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.OK); + void preflightRequestToEndpointShouldReturnOk() { + this.restTestClient.options().uri("/actuator/env").headers((headers) -> { + headers.set("Origin", "http://localhost:8080"); + headers.set("Access-Control-Request-Method", "GET"); + }).exchange().expectStatus().isOk(); } @Test - void preflightRequestWhenCorsConfigInvalidShouldReturnForbidden() throws Exception { - RequestEntity entity = RequestEntity.options(new URI("/actuator/env")) - .header("Origin", "http://localhost:9095") - .header("Access-Control-Request-Method", "GET") - .build(); - ResponseEntity exchange = this.testRestTemplate.exchange(entity, byte[].class); - assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); + void preflightRequestWhenCorsConfigInvalidShouldReturnForbidden() { + this.restTestClient.options().uri("/actuator/env").headers((headers) -> { + headers.set("Origin", "http://localhost:9095"); + headers.set("Access-Control-Request-Method", "GET"); + }).exchange().expectStatus().isForbidden(); } } diff --git a/smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementServerWithCustomBasePathAndWebEndpointsBasePathSampleActuatorApplicationTests.java b/smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementServerWithCustomBasePathAndWebEndpointsBasePathSampleActuatorApplicationTests.java index bb118f9fe39..3f6cad18a03 100644 --- a/smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementServerWithCustomBasePathAndWebEndpointsBasePathSampleActuatorApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementServerWithCustomBasePathAndWebEndpointsBasePathSampleActuatorApplicationTests.java @@ -19,14 +19,12 @@ package smoketest.actuator.customsecurity; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalManagementPort; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.context.ApplicationContext; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -53,10 +51,16 @@ class ManagementServerWithCustomBasePathAndWebEndpointsBasePathSampleActuatorApp @Test void testMissing() { - ResponseEntity entity = new TestRestTemplate("admin", "admin") - .getForEntity(getActuatorPath() + "/missing", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); - assertThat(entity.getBody()).contains("\"status\":404"); + RestTestClient.bindToServer() + .defaultHeaders((headers) -> headers.setBasicAuth("admin", "admin")) + .build() + .get() + .uri(getActuatorPath() + "/missing") + .exchange() + .expectStatus() + .isNotFound() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("\"status\":404")); } @Override diff --git a/smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementServerWithCustomBasePathSampleActuatorApplicationTests.java b/smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementServerWithCustomBasePathSampleActuatorApplicationTests.java index 20e1fdf2888..76cf1d4ae8e 100644 --- a/smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementServerWithCustomBasePathSampleActuatorApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementServerWithCustomBasePathSampleActuatorApplicationTests.java @@ -19,14 +19,12 @@ package smoketest.actuator.customsecurity; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalManagementPort; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.context.ApplicationContext; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -52,10 +50,16 @@ class ManagementServerWithCustomBasePathSampleActuatorApplicationTests @Test void testMissing() { - ResponseEntity entity = new TestRestTemplate("admin", "admin") - .getForEntity(getActuatorPath() + "/missing", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); - assertThat(entity.getBody()).contains("\"status\":404"); + RestTestClient.bindToServer() + .defaultHeaders((headers) -> headers.setBasicAuth("admin", "admin")) + .build() + .get() + .uri(getActuatorPath() + "/missing") + .exchange() + .expectStatus() + .isNotFound() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("\"status\":404")); } @Override diff --git a/smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementServerWithCustomServletPathSampleActuatorTests.java b/smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementServerWithCustomServletPathSampleActuatorTests.java index 9a2192d5557..4f2e4736a09 100644 --- a/smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementServerWithCustomServletPathSampleActuatorTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementServerWithCustomServletPathSampleActuatorTests.java @@ -19,15 +19,11 @@ package smoketest.actuator.customsecurity; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalManagementPort; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.context.ApplicationContext; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; - -import static org.assertj.core.api.Assertions.assertThat; +import org.springframework.test.web.servlet.client.RestTestClient; /** * Integration tests for a separate management server with a custom dispatcher servlet @@ -50,9 +46,13 @@ class ManagementServerWithCustomServletPathSampleActuatorTests extends AbstractS @Test void actuatorPathOnMainPortShouldNotMatch() { - ResponseEntity entity = new TestRestTemplate() - .getForEntity("http://localhost:" + this.port + "/example/actuator/health", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + RestTestClient.bindToServer() + .build() + .get() + .uri("http://localhost:" + this.port + "/example/actuator/health") + .exchange() + .expectStatus() + .isUnauthorized(); } @Override diff --git a/smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/SampleActuatorCustomSecurityApplicationTests.java b/smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/SampleActuatorCustomSecurityApplicationTests.java index 63bf2a83cee..5eab15313c4 100644 --- a/smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/SampleActuatorCustomSecurityApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/SampleActuatorCustomSecurityApplicationTests.java @@ -25,7 +25,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.context.ApplicationContext; import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; import static org.assertj.core.api.Assertions.assertThat; @@ -47,21 +46,21 @@ class SampleActuatorCustomSecurityApplicationTests extends AbstractSampleActuato private ApplicationContext applicationContext; @Test - @SuppressWarnings({ "rawtypes", "unchecked" }) + @SuppressWarnings("unchecked") void testInsecureApplicationPath() { - ResponseEntity entity = restTemplate().getForEntity(getPath() + "/foo", Map.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); - Map body = entity.getBody(); - assertThat(body).isNotNull(); - assertThat((String) body.get("message")).contains("Expected exception in controller"); + restTestClient().get() + .uri(getPath() + "/foo") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectBody(Map.class) + .value((body) -> assertThat((String) body.get("message")).contains("Expected exception in controller")); } @Test void mvcMatchersCanBeUsedToSecureActuators() { - ResponseEntity entity = beansRestTemplate().getForEntity(getActuatorPath() + "/beans", Object.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - entity = beansRestTemplate().getForEntity(getActuatorPath() + "/beans/", Object.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); + beansRestTestClient().get().uri(getActuatorPath() + "/beans").exchange().expectStatus().isOk(); + beansRestTestClient().get().uri(getActuatorPath() + "/beans/").exchange().expectStatus().isForbidden(); } @Override diff --git a/smoke-test/spring-boot-smoke-test-actuator-extension/src/test/java/smoketest/actuator/extension/SampleActuatorExtensionApplicationTests.java b/smoke-test/spring-boot-smoke-test-actuator-extension/src/test/java/smoketest/actuator/extension/SampleActuatorExtensionApplicationTests.java index d6db28f024c..2b82e3faeea 100644 --- a/smoke-test/spring-boot-smoke-test-actuator-extension/src/test/java/smoketest/actuator/extension/SampleActuatorExtensionApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator-extension/src/test/java/smoketest/actuator/extension/SampleActuatorExtensionApplicationTests.java @@ -16,60 +16,37 @@ package smoketest.actuator.extension; -import java.util.Map; - import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.restclient.RestTemplateBuilder; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.http.server.LocalTestWebServer; -import org.springframework.context.ApplicationContext; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; - -import static org.assertj.core.api.Assertions.assertThat; +import org.springframework.test.web.servlet.client.RestTestClient; @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "spring.web.error.include-message=always" }) -@AutoConfigureTestRestTemplate -@SuppressWarnings("removal") +@AutoConfigureRestTestClient class SampleActuatorExtensionApplicationTests { @Autowired - private ApplicationContext applicationContext; - - @Autowired - private TestRestTemplate restTemplate; - - @Autowired - private RestTemplateBuilder restTemplateBuilder; + private RestTestClient restTestClient; @Test - @SuppressWarnings("rawtypes") void healthActuatorIsNotExposed() { - ResponseEntity entity = this.restTemplate.getForEntity("/actuator/health", Map.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + this.restTestClient.get().uri("/actuator/health").exchange().expectStatus().isNotFound(); } @Test - @SuppressWarnings("rawtypes") void healthExtensionWithAuthHeaderIsDenied() { - ResponseEntity entity = this.restTemplate.getForEntity("/myextension/health", Map.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + this.restTestClient.get().uri("/myextension/health").exchange().expectStatus().isUnauthorized(); } @Test - @SuppressWarnings("rawtypes") void healthExtensionWithAuthHeader() { - TestRestTemplate restTemplate = new TestRestTemplate( - this.restTemplateBuilder.defaultHeader("Authorization", "Bearer secret")); - LocalTestWebServer localTestWebServer = LocalTestWebServer.obtain(this.applicationContext); - restTemplate.setUriTemplateHandler(localTestWebServer.uriBuilderFactory()); - ResponseEntity entity = restTemplate.getForEntity("/myextension/health", Map.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + RestTestClient restTestClient = this.restTestClient.mutate() + .defaultHeader("Authorization", "Bearer secret") + .build(); + restTestClient.get().uri("/myextension/health").exchange().expectStatus().isOk(); } } diff --git a/smoke-test/spring-boot-smoke-test-actuator-ui/src/test/java/smoketest/actuator/ui/SampleActuatorUiApplicationPortTests.java b/smoke-test/spring-boot-smoke-test-actuator-ui/src/test/java/smoketest/actuator/ui/SampleActuatorUiApplicationPortTests.java index b21301132e3..996a1169c9d 100644 --- a/smoke-test/spring-boot-smoke-test-actuator-ui/src/test/java/smoketest/actuator/ui/SampleActuatorUiApplicationPortTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator-ui/src/test/java/smoketest/actuator/ui/SampleActuatorUiApplicationPortTests.java @@ -16,19 +16,13 @@ package smoketest.actuator.ui; -import java.util.Map; - import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalManagementPort; import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -38,7 +32,6 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.server.port:0" }) -@AutoConfigureTestRestTemplate class SampleActuatorUiApplicationPortTests { @LocalServerPort @@ -47,30 +40,41 @@ class SampleActuatorUiApplicationPortTests { @LocalManagementPort private int managementPort; - @Autowired - private TestRestTemplate testRestTemplate; - @Test void testHome() { - ResponseEntity entity = this.testRestTemplate.getForEntity("http://localhost:" + this.port, - String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + RestTestClient.bindToServer() + .baseUrl("http://localhost:" + this.port) + .build() + .get() + .headers((headers) -> headers.setBasicAuth("user", getPassword())) + .exchange() + .expectStatus() + .isOk(); } @Test void testMetrics() { - @SuppressWarnings("rawtypes") - ResponseEntity entity = this.testRestTemplate - .getForEntity("http://localhost:" + this.managementPort + "/actuator/metrics", Map.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + RestTestClient.bindToServer() + .baseUrl("http://localhost:" + this.managementPort) + .build() + .get() + .uri("/actuator/metrics") + .exchange() + .expectStatus() + .isUnauthorized(); } @Test void testHealth() { - ResponseEntity entity = this.testRestTemplate.withBasicAuth("user", getPassword()) - .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("\"status\":\"UP\""); + RestTestClient.bindToServer() + .baseUrl("http://localhost:" + this.managementPort) + .defaultHeaders((headers) -> headers.setBasicAuth("user", getPassword())) + .build() + .get() + .uri("/actuator/health") + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("\"status\":\"UP\"")); } private String getPassword() { diff --git a/smoke-test/spring-boot-smoke-test-actuator-ui/src/test/java/smoketest/actuator/ui/SampleActuatorUiApplicationTests.java b/smoke-test/spring-boot-smoke-test-actuator-ui/src/test/java/smoketest/actuator/ui/SampleActuatorUiApplicationTests.java index 705474d3c5a..8082b6492dc 100644 --- a/smoke-test/spring-boot-smoke-test-actuator-ui/src/test/java/smoketest/actuator/ui/SampleActuatorUiApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator-ui/src/test/java/smoketest/actuator/ui/SampleActuatorUiApplicationTests.java @@ -16,22 +16,15 @@ package smoketest.actuator.ui; -import java.util.Arrays; -import java.util.Map; - import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -41,46 +34,51 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "spring.web.error.include-message=always" }) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleActuatorUiApplicationTests { @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @Test void testHome() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity entity = this.restTemplate.withBasicAuth("user", getPassword()) - .exchange("/", HttpMethod.GET, new HttpEntity<>(headers), String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("Hello"); + this.restTestClient.get() + .uri("/") + .accept(MediaType.TEXT_HTML) + .headers((headers) -> headers.setBasicAuth("user", getPassword())) + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("<title>Hello")); } @Test void testCss() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/css/bootstrap.min.css", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("body"); + this.restTestClient.get() + .uri("/css/bootstrap.min.css") + .headers((headers) -> headers.setBasicAuth("user", getPassword())) + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("body")); } @Test void testMetrics() { - @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate.getForEntity("/actuator/metrics", Map.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + this.restTestClient.get().uri("/actuator/metrics").exchange().expectStatus().isUnauthorized(); } @Test void testError() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()) - .exchange("/error", HttpMethod.GET, new HttpEntity<>(headers), String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); - assertThat(entity.getBody()).contains("<html>") - .contains("<body>") - .contains("Please contact the operator with the above information"); + this.restTestClient.get() + .uri("/error") + .accept(MediaType.TEXT_HTML) + .headers((headers) -> headers.setBasicAuth("user", getPassword())) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectBody(String.class) + .value((body) -> assertThat(body).contains("<html>") + .contains("<body>") + .contains("Please contact the operator with the above information")); } private String getPassword() { diff --git a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/AbstractManagementPortAndPathSampleActuatorApplicationTests.java b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/AbstractManagementPortAndPathSampleActuatorApplicationTests.java index 9dd7d56e2ba..2a5cd6b00c4 100644 --- a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/AbstractManagementPortAndPathSampleActuatorApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/AbstractManagementPortAndPathSampleActuatorApplicationTests.java @@ -21,12 +21,12 @@ import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; import org.springframework.boot.test.web.server.LocalManagementPort; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.core.env.Environment; import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -47,75 +47,99 @@ abstract class AbstractManagementPortAndPathSampleActuatorApplicationTests { private Environment environment; @Test + @SuppressWarnings("unchecked") void testHome() { - ResponseEntity<Map<String, Object>> entity = asMapEntity( - new TestRestTemplate("user", "password").getForEntity("http://localhost:" + this.port, Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).containsEntry("message", "Hello Phil"); + appPortClient().get() + .uri("/") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchangeSuccessfully() + .expectBody(Map.class) + .value((body) -> assertThat(body).containsEntry("message", "Hello Phil")); } @Test void testMetrics() { testHome(); // makes sure some requests have been made - ResponseEntity<Map<String, Object>> entity = asMapEntity(new TestRestTemplate() - .getForEntity("http://localhost:" + this.managementPort + "/admin/metrics", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + managementPortClient().get().uri("/admin/metrics").exchange().expectStatus().isUnauthorized(); } @Test void testHealth() { - ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/admin/health", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()) + managementPortClient().get() + .uri("/admin/health") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchangeSuccessfully() + .expectBody(String.class) .isEqualTo("{\"groups\":[\"comp\",\"live\",\"liveness\",\"readiness\",\"ready\"],\"status\":\"UP\"}"); } @Test void testGroupWithComposite() { - ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/admin/health/comp", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains( - "components\":{\"a\":{\"details\":{\"hello\":\"spring-a\"},\"status\":\"UP\"},\"c\":{\"details\":{\"hello\":\"spring-c\"},\"status\":\"UP\"}}"); + managementPortClient().get() + .uri("/admin/health/comp") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains( + "components\":{\"a\":{\"details\":{\"hello\":\"spring-a\"},\"status\":\"UP\"},\"c\":{\"details\":{\"hello\":\"spring-c\"},\"status\":\"UP\"}}")); } @Test void testEnvNotFound() { String unknownProperty = "test-does-not-exist"; assertThat(this.environment.containsProperty(unknownProperty)).isFalse(); - ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/admin/env/" + unknownProperty, String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + managementPortClient().get() + .uri("/admin/env/" + unknownProperty) + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchange() + .expectStatus() + .isNotFound(); } @Test + @SuppressWarnings("unchecked") void testMissing() { - ResponseEntity<String> entity = new TestRestTemplate("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/admin/missing", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); - assertThat(entity.getBody()).contains("\"status\":404"); + managementPortClient().get() + .uri("/admin/missing") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchange() + .expectStatus() + .isNotFound() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("\"status\":404")); } @Test + @SuppressWarnings("unchecked") void testErrorPage() { - ResponseEntity<Map<String, Object>> entity = asMapEntity(new TestRestTemplate("user", "password") - .getForEntity("http://localhost:" + this.port + "/error", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); - assertThat(entity.getBody()).containsEntry("status", 999); + appPortClient().get() + .uri("/error") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectBody(Map.class) + .value((body) -> assertThat(body).containsEntry("status", 999)); } @Test + @SuppressWarnings("unchecked") void testManagementErrorPage() { - ResponseEntity<Map<String, Object>> entity = asMapEntity(new TestRestTemplate("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/error", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).containsEntry("status", 999); + managementPortClient().get() + .uri("/error") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchangeSuccessfully() + .expectBody(Map.class) + .value((body) -> assertThat(body).containsEntry("status", 999)); } - @SuppressWarnings({ "unchecked", "rawtypes" }) - static <K, V> ResponseEntity<Map<K, V>> asMapEntity(ResponseEntity<Map> entity) { - return (ResponseEntity) entity; + RestTestClient appPortClient() { + return RestTestClient.bindToServer().baseUrl("http://localhost:" + this.port).build(); + } + + RestTestClient managementPortClient() { + return RestTestClient.bindToServer().baseUrl("http://localhost:" + this.managementPort).build(); } } diff --git a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/CorsSampleActuatorApplicationTests.java b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/CorsSampleActuatorApplicationTests.java index 4092432ca45..5e0e964eebd 100644 --- a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/CorsSampleActuatorApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/CorsSampleActuatorApplicationTests.java @@ -16,25 +16,13 @@ package smoketest.actuator; -import java.net.URI; -import java.util.Map; - -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.restclient.RestTemplateBuilder; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.http.server.LocalTestWebServer; -import org.springframework.context.ApplicationContext; -import org.springframework.http.HttpStatus; -import org.springframework.http.RequestEntity; -import org.springframework.http.ResponseEntity; import org.springframework.test.context.ActiveProfiles; - -import static org.assertj.core.api.Assertions.assertThat; +import org.springframework.test.web.servlet.client.RestTestClient; /** * Integration test for cors preflight requests to management endpoints. @@ -43,47 +31,31 @@ import static org.assertj.core.api.Assertions.assertThat; */ @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("cors") -@AutoConfigureTestRestTemplate -@SuppressWarnings("removal") +@AutoConfigureRestTestClient class CorsSampleActuatorApplicationTests { - private TestRestTemplate testRestTemplate; - @Autowired - private ApplicationContext applicationContext; - - @BeforeEach - void setUp() { - RestTemplateBuilder builder = new RestTemplateBuilder(); - LocalTestWebServer localTestWebServer = LocalTestWebServer.obtain(this.applicationContext); - builder = builder.uriTemplateHandler(localTestWebServer.uriBuilderFactory()); - this.testRestTemplate = new TestRestTemplate(builder); - } + private RestTestClient restTestClient; @Test void endpointShouldReturnUnauthorized() { - ResponseEntity<?> entity = this.testRestTemplate.getForEntity("/actuator/env", Map.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + this.restTestClient.get().uri("/actuator/env").exchange().expectStatus().isUnauthorized(); } @Test - void preflightRequestToEndpointShouldReturnOk() throws Exception { - RequestEntity<?> healthRequest = RequestEntity.options(new URI("/actuator/env")) - .header("Origin", "http://localhost:8080") - .header("Access-Control-Request-Method", "GET") - .build(); - ResponseEntity<?> exchange = this.testRestTemplate.exchange(healthRequest, Map.class); - assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.OK); + void preflightRequestToEndpointShouldReturnOk() { + this.restTestClient.options().uri("/actuator/env").headers((headers) -> { + headers.set("Origin", "http://localhost:8080"); + headers.set("Access-Control-Request-Method", "GET"); + }).exchange().expectStatus().isOk(); } @Test - void preflightRequestWhenCorsConfigInvalidShouldReturnForbidden() throws Exception { - RequestEntity<?> entity = RequestEntity.options(new URI("/actuator/env")) - .header("Origin", "http://localhost:9095") - .header("Access-Control-Request-Method", "GET") - .build(); - ResponseEntity<byte[]> exchange = this.testRestTemplate.exchange(entity, byte[].class); - assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); + void preflightRequestWhenCorsConfigInvalidShouldReturnForbidden() { + this.restTestClient.options().uri("/actuator/env").headers((headers) -> { + headers.set("Origin", "http://localhost:9095"); + headers.set("Access-Control-Request-Method", "GET"); + }).exchange().expectStatus().isForbidden(); } } diff --git a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/EndpointsPropertiesSampleActuatorApplicationTests.java b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/EndpointsPropertiesSampleActuatorApplicationTests.java index 9e56bc3dfe9..6cbd15be879 100644 --- a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/EndpointsPropertiesSampleActuatorApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/EndpointsPropertiesSampleActuatorApplicationTests.java @@ -21,13 +21,12 @@ import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -38,34 +37,38 @@ import static org.assertj.core.api.Assertions.assertThat; */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @ActiveProfiles("endpoints") -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class EndpointsPropertiesSampleActuatorApplicationTests { @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @Test + @SuppressWarnings("unchecked") void testCustomErrorPath() { - ResponseEntity<Map<String, Object>> entity = asMapEntity( - this.restTemplate.withBasicAuth("user", "password").getForEntity("/oops", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); - Map<String, Object> body = entity.getBody(); - assertThat(body).containsEntry("error", "None"); - assertThat(body).containsEntry("status", 999); + this.restTestClient.get() + .uri("/oops") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectBody(Map.class) + .value((body) -> { + assertThat(body).containsEntry("error", "None"); + assertThat(body).containsEntry("status", 999); + }); } @Test void testCustomContextPath() { - ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", "password") - .getForEntity("/admin/health", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("\"status\":\"UP\""); - assertThat(entity.getBody()).contains("\"hello\":\"world\""); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - static <K, V> ResponseEntity<Map<K, V>> asMapEntity(ResponseEntity<Map> entity) { - return (ResponseEntity) entity; + this.restTestClient.get() + .uri("/admin/health") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("\"status\":\"UP\"").contains("\"hello\":\"world\"")); } } diff --git a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementAddressActuatorApplicationTests.java b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementAddressActuatorApplicationTests.java index 7bb749e1333..db3495ccb54 100644 --- a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementAddressActuatorApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementAddressActuatorApplicationTests.java @@ -16,17 +16,13 @@ package smoketest.actuator; -import java.util.Map; - import org.junit.jupiter.api.Test; -import org.springframework.boot.resttestclient.TestRestTemplate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalManagementPort; import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -47,22 +43,27 @@ class ManagementAddressActuatorApplicationTests { @Test void testHome() { - ResponseEntity<Map<String, Object>> entity = asMapEntity( - new TestRestTemplate().getForEntity("http://localhost:" + this.port, Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + RestTestClient.bindToServer() + .baseUrl("http://localhost:" + this.port) + .build() + .get() + .uri("/") + .exchange() + .expectStatus() + .isUnauthorized(); } @Test void testHealth() { - ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/admin/actuator/health", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("\"status\":\"UP\""); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - static <K, V> ResponseEntity<Map<K, V>> asMapEntity(ResponseEntity<Map> entity) { - return (ResponseEntity) entity; + RestTestClient.bindToServer() + .baseUrl("http://localhost:" + this.managementPort) + .defaultHeaders((headers) -> headers.setBasicAuth("user", "password")) + .build() + .get() + .uri("/admin/actuator/health") + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("\"status\":\"UP\"")); } } diff --git a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementDifferentPortAndEndpointWithExceptionHandlerSampleActuatorApplicationTests.java b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementDifferentPortAndEndpointWithExceptionHandlerSampleActuatorApplicationTests.java index c3c52cc205c..d7b5ee61019 100644 --- a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementDifferentPortAndEndpointWithExceptionHandlerSampleActuatorApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementDifferentPortAndEndpointWithExceptionHandlerSampleActuatorApplicationTests.java @@ -18,15 +18,12 @@ package smoketest.actuator; import org.junit.jupiter.api.Test; -import org.springframework.boot.resttestclient.TestRestTemplate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalManagementPort; import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import org.springframework.web.bind.annotation.ExceptionHandler; -import static org.assertj.core.api.Assertions.assertThat; - /** * Integration tests for separate management and main service ports with Actuator's MVC * {@link org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint @@ -43,10 +40,17 @@ class ManagementDifferentPortAndEndpointWithExceptionHandlerSampleActuatorApplic @Test void testExceptionHandlerRestControllerEndpoint() { - ResponseEntity<String> entity = new TestRestTemplate("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/actuator/exception", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.EXPECTATION_FAILED); - assertThat(entity.getBody()).isEqualTo("this is a custom exception body"); + RestTestClient.bindToServer() + .baseUrl("http://localhost:" + this.managementPort) + .defaultHeaders((headers) -> headers.setBasicAuth("user", "password")) + .build() + .get() + .uri("/actuator/exception") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.EXPECTATION_FAILED) + .expectBody(String.class) + .isEqualTo("this is a custom exception body"); } } diff --git a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementDifferentPortSampleActuatorApplicationTests.java b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementDifferentPortSampleActuatorApplicationTests.java index 3168a90d328..01f0c0f09ea 100644 --- a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementDifferentPortSampleActuatorApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementDifferentPortSampleActuatorApplicationTests.java @@ -18,11 +18,9 @@ package smoketest.actuator; import org.junit.jupiter.api.Test; -import org.springframework.boot.resttestclient.TestRestTemplate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalManagementPort; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -41,10 +39,15 @@ class ManagementDifferentPortSampleActuatorApplicationTests { @Test void linksEndpointShouldBeAvailable() { - ResponseEntity<String> entity = new TestRestTemplate("user", "password") - .getForEntity("http://localhost:" + this.managementPort, String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("\"_links\""); + RestTestClient.bindToServer() + .baseUrl("http://localhost:" + this.managementPort) + .defaultHeaders((headers) -> headers.setBasicAuth("user", "password")) + .build() + .get() + .uri("/") + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("\"_links\"")); } } diff --git a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPathSampleActuatorApplicationTests.java b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPathSampleActuatorApplicationTests.java index ce13d3bf200..f5da731ee04 100644 --- a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPathSampleActuatorApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPathSampleActuatorApplicationTests.java @@ -16,17 +16,14 @@ package smoketest.actuator; -import java.util.Map; - import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -37,30 +34,32 @@ import static org.assertj.core.api.Assertions.assertThat; */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.endpoints.web.base-path=/admin" }) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class ManagementPathSampleActuatorApplicationTests { @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @Test void testHealth() { - ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", "password") - .getForEntity("/admin/health", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("\"status\":\"UP\""); + this.restTestClient.get() + .uri("/admin/health") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("\"status\":\"UP\"")); } @Test void testHomeIsSecure() { - ResponseEntity<Map<String, Object>> entity = asMapEntity(this.restTemplate.getForEntity("/", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); - assertThat(entity.getHeaders().headerNames()).doesNotContain("Set-Cookie"); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - static <K, V> ResponseEntity<Map<K, V>> asMapEntity(ResponseEntity<Map> entity) { - return (ResponseEntity) entity; + this.restTestClient.get() + .uri("/") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isUnauthorized() + .expectHeader() + .doesNotExist("Set-Cookie"); } } diff --git a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPortSampleActuatorApplicationTests.java b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPortSampleActuatorApplicationTests.java index dd241cb70c7..8e57fdb9ce3 100644 --- a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPortSampleActuatorApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPortSampleActuatorApplicationTests.java @@ -23,7 +23,6 @@ import org.junit.jupiter.api.Test; import smoketest.actuator.ManagementPortSampleActuatorApplicationTests.CustomErrorAttributes; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalManagementPort; @@ -32,9 +31,9 @@ import org.springframework.boot.web.error.ErrorAttributeOptions; import org.springframework.boot.webmvc.error.DefaultErrorAttributes; import org.springframework.context.annotation.Import; import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.web.servlet.client.RestTestClient; import org.springframework.web.context.request.WebRequest; import static org.assertj.core.api.Assertions.assertThat; @@ -59,53 +58,78 @@ class ManagementPortSampleActuatorApplicationTests { private CustomErrorAttributes errorAttributes; @Test + @SuppressWarnings("unchecked") void testHome() { - ResponseEntity<Map<String, Object>> entity = asMapEntity( - new TestRestTemplate("user", "password").getForEntity("http://localhost:" + this.port, Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).containsEntry("message", "Hello Phil"); + RestTestClient.bindToServer() + .baseUrl("http://localhost:" + this.port) + .defaultHeaders((headers) -> headers.setBasicAuth("user", "password")) + .build() + .get() + .uri("/") + .exchangeSuccessfully() + .expectBody(Map.class) + .value((body) -> assertThat(body).containsEntry("message", "Hello Phil")); } @Test void testMetrics() { testHome(); // makes sure some requests have been made - ResponseEntity<Map<String, Object>> entity = asMapEntity(new TestRestTemplate() - .getForEntity("http://localhost:" + this.managementPort + "/actuator/metrics", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + RestTestClient.bindToServer() + .baseUrl("http://localhost:" + this.managementPort) + .build() + .get() + .uri("/actuator/metrics") + .exchange() + .expectStatus() + .isUnauthorized(); } @Test void testHealth() { - ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("\"status\":\"UP\""); - assertThat(entity.getBody()).contains("\"example\""); - assertThat(entity.getBody()).contains("\"counter\":42"); + RestTestClient.bindToServer() + .baseUrl("http://localhost:" + this.managementPort) + .defaultHeaders((headers) -> headers.setBasicAuth("user", "password")) + .build() + .get() + .uri("/actuator/health") + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("\"status\":\"UP\"") + .contains("\"example\"") + .contains("\"counter\":42")); } @Test + @SuppressWarnings("unchecked") void testErrorPage() { - ResponseEntity<Map<String, Object>> entity = asMapEntity(new TestRestTemplate("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/error", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).containsEntry("status", 999); + RestTestClient.bindToServer() + .baseUrl("http://localhost:" + this.managementPort) + .defaultHeaders((headers) -> headers.setBasicAuth("user", "password")) + .build() + .get() + .uri("/error") + .exchangeSuccessfully() + .expectBody(Map.class) + .value((body) -> assertThat(body).containsEntry("status", 999)); } @Test + @SuppressWarnings("unchecked") void securityContextIsAvailableToErrorHandling() { this.errorAttributes.securityContext = null; - ResponseEntity<Map<String, Object>> entity = asMapEntity(new TestRestTemplate("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/404", Map.class)); + RestTestClient.bindToServer() + .baseUrl("http://localhost:" + this.managementPort) + .defaultHeaders((headers) -> headers.setBasicAuth("user", "password")) + .build() + .get() + .uri("/404") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.NOT_FOUND) + .expectBody(Map.class) + .value((body) -> assertThat(body).containsEntry("status", 404)); assertThat(this.errorAttributes.securityContext).isNotNull(); assertThat(this.errorAttributes.securityContext.getAuthentication()).isNotNull(); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); - assertThat(entity.getBody()).containsEntry("status", 404); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - static <K, V> ResponseEntity<Map<K, V>> asMapEntity(ResponseEntity<Map> entity) { - return (ResponseEntity) entity; } static class CustomErrorAttributes extends DefaultErrorAttributes { diff --git a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPortWithLazyInitializationTests.java b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPortWithLazyInitializationTests.java index 69e03630aee..2f298c7ae36 100644 --- a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPortWithLazyInitializationTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPortWithLazyInitializationTests.java @@ -18,11 +18,9 @@ package smoketest.actuator; import org.junit.jupiter.api.Test; -import org.springframework.boot.resttestclient.TestRestTemplate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalManagementPort; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -41,10 +39,15 @@ class ManagementPortWithLazyInitializationTests { @Test void testHealth() { - ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("\"status\":\"UP\""); + RestTestClient.bindToServer() + .baseUrl("http://localhost:" + this.managementPort) + .defaultHeaders((headers) -> headers.setBasicAuth("user", "password")) + .build() + .get() + .uri("/actuator/health") + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("\"status\":\"UP\"")); } } diff --git a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementRandomPortWithConfiguredPortSampleActuatorApplicationTests.java b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementRandomPortWithConfiguredPortSampleActuatorApplicationTests.java index 8ce53f3fd59..60563cb1136 100644 --- a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementRandomPortWithConfiguredPortSampleActuatorApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementRandomPortWithConfiguredPortSampleActuatorApplicationTests.java @@ -18,12 +18,10 @@ package smoketest.actuator; import org.junit.jupiter.api.Test; -import org.springframework.boot.resttestclient.TestRestTemplate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalManagementPort; import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -56,10 +54,15 @@ class ManagementRandomPortWithConfiguredPortSampleActuatorApplicationTests { @Test void testHealth() { - ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("\"status\":\"UP\""); + RestTestClient.bindToServer() + .baseUrl("http://localhost:" + this.managementPort) + .defaultHeaders((headers) -> headers.setBasicAuth("user", "password")) + .build() + .get() + .uri("/actuator/health") + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("\"status\":\"UP\"")); } } diff --git a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/NoManagementSampleActuatorApplicationTests.java b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/NoManagementSampleActuatorApplicationTests.java index 7f4d0bf6cf7..f4623b57ebf 100644 --- a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/NoManagementSampleActuatorApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/NoManagementSampleActuatorApplicationTests.java @@ -21,12 +21,10 @@ import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -36,31 +34,32 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.server.port=-1" }) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class NoManagementSampleActuatorApplicationTests { @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @Test + @SuppressWarnings("unchecked") void testHome() { - ResponseEntity<Map<String, Object>> entity = asMapEntity( - this.restTemplate.withBasicAuth("user", "password").getForEntity("/", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).containsEntry("message", "Hello Phil"); + this.restTestClient.get() + .uri("/") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchangeSuccessfully() + .expectBody(Map.class) + .value((body) -> assertThat(body).containsEntry("message", "Hello Phil")); } @Test void testMetricsNotAvailable() { testHome(); // makes sure some requests have been made - ResponseEntity<Map<String, Object>> entity = asMapEntity( - this.restTemplate.withBasicAuth("user", "password").getForEntity("/metrics", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - static <K, V> ResponseEntity<Map<K, V>> asMapEntity(ResponseEntity<Map> entity) { - return (ResponseEntity) entity; + this.restTestClient.get() + .uri("/metrics") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchange() + .expectStatus() + .isNotFound(); } } diff --git a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationIsolatedJsonMapperFalseTests.java b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationIsolatedJsonMapperFalseTests.java index caf10be6f74..1bc7446b644 100644 --- a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationIsolatedJsonMapperFalseTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationIsolatedJsonMapperFalseTests.java @@ -20,15 +20,11 @@ import org.junit.jupiter.api.Test; import tools.jackson.databind.json.JsonMapper; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; import org.springframework.test.context.ContextConfiguration; - -import static org.assertj.core.api.Assertions.assertThat; +import org.springframework.test.web.servlet.client.RestTestClient; /** * Integration test for WebMVC actuator when not using an isolated {@link JsonMapper}. @@ -39,18 +35,20 @@ import static org.assertj.core.api.Assertions.assertThat; properties = { "management.endpoints.jackson.isolated-json-mapper=false", "spring.jackson.mapper.require-setters-for-getters=true" }) @ContextConfiguration(loader = ApplicationStartupSpringBootContextLoader.class) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleActuatorApplicationIsolatedJsonMapperFalseTests { @Autowired - private TestRestTemplate testRestTemplate; + private RestTestClient restTestClient; @Test void bodyIsEmptyDueToMainJsonMapperRequiringSettersForGetters() { - ResponseEntity<String> entity = this.testRestTemplate.withBasicAuth("user", "password") - .getForEntity("/actuator/startup", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).isEqualTo("{}"); + this.restTestClient.get() + .uri("/actuator/startup") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchangeSuccessfully() + .expectBody(String.class) + .isEqualTo("{}"); } } diff --git a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationIsolatedJsonMapperTrueTests.java b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationIsolatedJsonMapperTrueTests.java index 9a137e29f36..0c8eb9861ba 100644 --- a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationIsolatedJsonMapperTrueTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationIsolatedJsonMapperTrueTests.java @@ -20,13 +20,11 @@ import org.junit.jupiter.api.Test; import tools.jackson.databind.json.JsonMapper; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -39,18 +37,20 @@ import static org.assertj.core.api.Assertions.assertThat; properties = { "management.endpoints.jackson.isolated-json-mapper=true", "spring.jackson.mapper.require-setters-for-getters=true" }) @ContextConfiguration(loader = ApplicationStartupSpringBootContextLoader.class) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleActuatorApplicationIsolatedJsonMapperTrueTests { @Autowired - private TestRestTemplate testRestTemplate; + private RestTestClient restTestClient; @Test void bodyIsPresentAsOnlyMainObjectMapperRequiresSettersForGetters() { - ResponseEntity<String> entity = this.testRestTemplate.withBasicAuth("user", "password") - .getForEntity("/actuator/startup", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("\"timeline\":"); + this.restTestClient.get() + .uri("/actuator/startup") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("\"timeline\":")); } } diff --git a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationTests.java b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationTests.java index b830fdf540c..63d8b5f4c40 100644 --- a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationTests.java @@ -16,7 +16,6 @@ package smoketest.actuator; -import java.util.Arrays; import java.util.List; import java.util.Map; @@ -24,17 +23,13 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.jdbc.autoconfigure.DataSourceProperties; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.context.ApplicationContext; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; @@ -46,160 +41,188 @@ import static org.assertj.core.api.Assertions.entry; * @author Stephane Nicoll */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleActuatorApplicationTests { @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @Autowired private ApplicationContext applicationContext; @Test void testHomeIsSecure() { - ResponseEntity<Map<String, Object>> entity = asMapEntity(this.restTemplate.getForEntity("/", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); - assertThat(entity.getHeaders().headerNames()).doesNotContain("Set-Cookie"); + this.restTestClient.get() + .uri("/") + .exchange() + .expectStatus() + .isUnauthorized() + .expectHeader() + .doesNotExist("Set-Cookie"); } @Test void testMetricsIsSecure() { - ResponseEntity<Map<String, Object>> entity = asMapEntity( - this.restTemplate.getForEntity("/actuator/metrics", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); - entity = asMapEntity(this.restTemplate.getForEntity("/actuator/metrics/", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); - entity = asMapEntity(this.restTemplate.getForEntity("/actuator/metrics/foo", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); - entity = asMapEntity(this.restTemplate.getForEntity("/actuator/metrics.json", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + this.restTestClient.get().uri("/actuator/metrics").exchange().expectStatus().isUnauthorized(); + this.restTestClient.get().uri("/actuator/metrics/").exchange().expectStatus().isUnauthorized(); + this.restTestClient.get().uri("/actuator/metrics/foo").exchange().expectStatus().isUnauthorized(); + this.restTestClient.get().uri("/actuator/metrics.json").exchange().expectStatus().isUnauthorized(); } @Test + @SuppressWarnings("unchecked") void testHome() { - ResponseEntity<Map<String, Object>> entity = asMapEntity( - this.restTemplate.withBasicAuth("user", "password").getForEntity("/", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).containsEntry("message", "Hello Phil"); + this.restTestClient.get() + .uri("/") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchangeSuccessfully() + .expectBody(Map.class) + .value((body) -> assertThat(body).containsEntry("message", "Hello Phil")); } @Test @SuppressWarnings("unchecked") void testMetrics() { testHome(); // makes sure some requests have been made - ResponseEntity<Map<String, Object>> entity = asMapEntity( - this.restTemplate.withBasicAuth("user", "password").getForEntity("/actuator/metrics", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - Map<String, Object> body = entity.getBody(); - assertThat(body).isNotNull(); - assertThat(body).containsKey("names"); - List<String> names = (List<String>) body.get("names"); - assertThat(names).contains("jvm.buffer.count"); + this.restTestClient.get() + .uri("/actuator/metrics") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchangeSuccessfully() + .expectBody(Map.class) + .value((body) -> { + assertThat(body).containsKey("names"); + List<String> names = (List<String>) body.get("names"); + assertThat(names).contains("jvm.buffer.count"); + }); } @Test + @SuppressWarnings("unchecked") void testEnv() { - ResponseEntity<Map<String, Object>> entity = asMapEntity( - this.restTemplate.withBasicAuth("user", "password").getForEntity("/actuator/env", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).containsKey("propertySources"); + this.restTestClient.get() + .uri("/actuator/env") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchangeSuccessfully() + .expectBody(Map.class) + .value((body) -> assertThat(body).containsKey("propertySources")); } @Test void healthInsecureByDefault() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/actuator/health", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("\"status\":\"UP\""); - assertThat(entity.getBody()).doesNotContain("\"hello\":\"1\""); + this.restTestClient.get() + .uri("/actuator/health") + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("\"status\":\"UP\"").doesNotContain("\"hello\":\"1\"")); } @Test void testErrorPage() { - ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", "password") - .getForEntity("/foo", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); - String body = entity.getBody(); - assertThat(body).contains("\"error\":"); + this.restTestClient.get() + .uri("/foo") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectBody(String.class) + .value((body) -> assertThat(body).contains("\"error\":")); } @Test void testHtmlErrorPage() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - HttpEntity<?> request = new HttpEntity<Void>(headers); - ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", "password") - .exchange("/foo", HttpMethod.GET, request, String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); - String body = entity.getBody(); - assertThat(body).as("Body was null").isNotNull(); - assertThat(body).contains("This application has no explicit mapping for /error"); + this.restTestClient.get() + .uri("/foo") + .accept(MediaType.TEXT_HTML) + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectBody(String.class) + .value((body) -> assertThat(body).as("Body was null") + .isNotNull() + .contains("This application has no explicit mapping for /error")); } @Test + @SuppressWarnings("unchecked") void testErrorPageDirectAccess() { - ResponseEntity<Map<String, Object>> entity = asMapEntity( - this.restTemplate.withBasicAuth("user", "password").getForEntity("/error", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); - assertThat(entity.getBody()).containsEntry("error", "None"); - assertThat(entity.getBody()).containsEntry("status", 999); + this.restTestClient.get() + .uri("/error") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectBody(Map.class) + .value((body) -> { + assertThat(body).containsEntry("error", "None"); + assertThat(body).containsEntry("status", 999); + }); } @Test + @SuppressWarnings("unchecked") void testBeans() { - ResponseEntity<Map<String, Object>> entity = asMapEntity( - this.restTemplate.withBasicAuth("user", "password").getForEntity("/actuator/beans", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).containsOnlyKeys("contexts"); + this.restTestClient.get() + .uri("/actuator/beans") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchangeSuccessfully() + .expectBody(Map.class) + .value((body) -> assertThat(body).containsOnlyKeys("contexts")); } @Test @SuppressWarnings("unchecked") void testConfigProps() { - ResponseEntity<Map<String, Object>> entity = asMapEntity( - this.restTemplate.withBasicAuth("user", "password").getForEntity("/actuator/configprops", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - Map<String, Object> body = entity.getBody(); - assertThat(body).isNotNull(); - Map<String, Object> contexts = (Map<String, Object>) body.get("contexts"); - assertThat(contexts).isNotNull(); - Map<String, Object> context = (Map<String, Object>) contexts.get(this.applicationContext.getId()); - assertThat(context).isNotNull(); - Map<String, Object> beans = (Map<String, Object>) context.get("beans"); - assertThat(beans).containsKey("spring.datasource-" + DataSourceProperties.class.getName()); + this.restTestClient.get() + .uri("/actuator/configprops") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchangeSuccessfully() + .expectBody(Map.class) + .value((body) -> { + Map<String, Object> contexts = (Map<String, Object>) body.get("contexts"); + assertThat(contexts).isNotNull(); + Map<String, Object> context = (Map<String, Object>) contexts.get(this.applicationContext.getId()); + assertThat(context).isNotNull(); + Map<String, Object> beans = (Map<String, Object>) context.get("beans"); + assertThat(beans).containsKey("spring.datasource-" + DataSourceProperties.class.getName()); + }); } @Test + @SuppressWarnings("unchecked") void testLegacyDot() { - ResponseEntity<Map<String, Object>> entity = asMapEntity( - this.restTemplate.withBasicAuth("user", "password").getForEntity("/actuator/legacy", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains(entry("legacy", "legacy")); + this.restTestClient.get() + .uri("/actuator/legacy") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchangeSuccessfully() + .expectBody(Map.class) + .value((body) -> assertThat(body).contains(entry("legacy", "legacy"))); } @Test + @SuppressWarnings("unchecked") void testLegacyHyphen() { - ResponseEntity<Map<String, Object>> entity = asMapEntity( - this.restTemplate.withBasicAuth("user", "password").getForEntity("/actuator/anotherlegacy", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains(entry("legacy", "legacy")); + this.restTestClient.get() + .uri("/actuator/anotherlegacy") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchangeSuccessfully() + .expectBody(Map.class) + .value((body) -> assertThat(body).contains(entry("legacy", "legacy"))); } @Test @SuppressWarnings("unchecked") void testInfo() { - ResponseEntity<Map<String, Object>> entity = asMapEntity( - this.restTemplate.withBasicAuth("user", "password").getForEntity("/actuator/info", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).containsKey("build"); - Map<String, Object> body = entity.getBody(); - assertThat(body).isNotNull(); - Map<String, Object> example = (Map<String, Object>) body.get("example"); - assertThat(example).containsEntry("someKey", "someValue"); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - static <K, V> ResponseEntity<Map<K, V>> asMapEntity(ResponseEntity<Map> entity) { - return (ResponseEntity) entity; + this.restTestClient.get() + .uri("/actuator/info") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchangeSuccessfully() + .expectBody(Map.class) + .value((body) -> { + assertThat(body).containsKey("build"); + Map<String, Object> example = (Map<String, Object>) body.get("example"); + assertThat(example).containsEntry("someKey", "someValue"); + }); } } diff --git a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ServletPathSampleActuatorApplicationTests.java b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ServletPathSampleActuatorApplicationTests.java index c6343815278..9acc8f4a2b6 100644 --- a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ServletPathSampleActuatorApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ServletPathSampleActuatorApplicationTests.java @@ -21,12 +21,12 @@ import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -36,39 +36,48 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "spring.mvc.servlet.path=/spring" }) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class ServletPathSampleActuatorApplicationTests { @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @Test + @SuppressWarnings("unchecked") void testErrorPath() { - ResponseEntity<Map<String, Object>> entity = asMapEntity( - this.restTemplate.withBasicAuth("user", "password").getForEntity("/spring/error", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); - assertThat(entity.getBody()).containsEntry("error", "None"); - assertThat(entity.getBody()).containsEntry("status", 999); + this.restTestClient.get() + .uri("/spring/error") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectBody(Map.class) + .value((body) -> { + assertThat(body).containsEntry("error", "None"); + assertThat(body).containsEntry("status", 999); + }); } @Test void testHealth() { - ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", "password") - .getForEntity("/spring/actuator/health", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("\"status\":\"UP\""); + this.restTestClient.get() + .uri("/spring/actuator/health") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("\"status\":\"UP\"")); } @Test void testHomeIsSecure() { - ResponseEntity<Map<String, Object>> entity = asMapEntity(this.restTemplate.getForEntity("/spring/", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); - assertThat(entity.getHeaders().headerNames()).doesNotContain("Set-Cookie"); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - static <K, V> ResponseEntity<Map<K, V>> asMapEntity(ResponseEntity<Map> entity) { - return (ResponseEntity) entity; + this.restTestClient.get() + .uri("/spring/") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isUnauthorized() + .expectHeader() + .doesNotExist("Set-Cookie"); } } diff --git a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ShutdownSampleActuatorApplicationTests.java b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ShutdownSampleActuatorApplicationTests.java index 76849f91cbf..5e6bdf77446 100644 --- a/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ShutdownSampleActuatorApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ShutdownSampleActuatorApplicationTests.java @@ -21,18 +21,16 @@ import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer; import org.springframework.security.web.SecurityFilterChain; import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -43,35 +41,33 @@ import static org.assertj.core.api.Assertions.assertThat; */ @SpringBootTest(classes = { ShutdownSampleActuatorApplicationTests.SecurityConfiguration.class, SampleActuatorApplication.class }, webEnvironment = WebEnvironment.RANDOM_PORT) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class ShutdownSampleActuatorApplicationTests { @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @Test + @SuppressWarnings("unchecked") void testHome() { - ResponseEntity<Map<String, Object>> entity = asMapEntity( - this.restTemplate.withBasicAuth("user", "password").getForEntity("/", Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - Map<String, Object> body = entity.getBody(); - assertThat(body).containsEntry("message", "Hello Phil"); + this.restTestClient.get() + .uri("/") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchangeSuccessfully() + .expectBody(Map.class) + .value((body) -> assertThat(body).containsEntry("message", "Hello Phil")); } @Test @DirtiesContext + @SuppressWarnings("unchecked") void testShutdown() { - ResponseEntity<Map<String, Object>> entity = asMapEntity(this.restTemplate.withBasicAuth("user", "password") - .postForEntity("/actuator/shutdown", null, Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - Map<String, Object> body = entity.getBody(); - assertThat(body).isNotNull(); - assertThat(((String) body.get("message"))).contains("Shutting down"); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - static <K, V> ResponseEntity<Map<K, V>> asMapEntity(ResponseEntity<Map> entity) { - return (ResponseEntity) entity; + this.restTestClient.post() + .uri("/actuator/shutdown") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchangeSuccessfully() + .expectBody(Map.class) + .value((body) -> assertThat((String) body.get("message")).contains("Shutting down")); } @Configuration(proxyBeanMethods = false) diff --git a/smoke-test/spring-boot-smoke-test-devtools/src/test/java/smoketest/devtools/SampleDevToolsApplicationIntegrationTests.java b/smoke-test/spring-boot-smoke-test-devtools/src/test/java/smoketest/devtools/SampleDevToolsApplicationIntegrationTests.java index 641dcbc1809..3399c708e3b 100644 --- a/smoke-test/spring-boot-smoke-test-devtools/src/test/java/smoketest/devtools/SampleDevToolsApplicationIntegrationTests.java +++ b/smoke-test/spring-boot-smoke-test-devtools/src/test/java/smoketest/devtools/SampleDevToolsApplicationIntegrationTests.java @@ -19,12 +19,10 @@ package smoketest.devtools; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -35,30 +33,33 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleDevToolsApplicationIntegrationTests { @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @Test void testStaticResource() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/css/application.css", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("color: green;"); + this.restTestClient.get() + .uri("/css/application.css") + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("color: green;")); } @Test void testPublicResource() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/public.txt", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("public file"); + this.restTestClient.get() + .uri("/public.txt") + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("public file")); } @Test void testClassResource() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/application.properties", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + this.restTestClient.get().uri("/application.properties").exchange().expectStatus().isNotFound(); } } diff --git a/smoke-test/spring-boot-smoke-test-hateoas/src/test/java/smoketest/hateoas/SampleHateoasApplicationTests.java b/smoke-test/spring-boot-smoke-test-hateoas/src/test/java/smoketest/hateoas/SampleHateoasApplicationTests.java index c101d801447..5cfb9134755 100644 --- a/smoke-test/spring-boot-smoke-test-hateoas/src/test/java/smoketest/hateoas/SampleHateoasApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-hateoas/src/test/java/smoketest/hateoas/SampleHateoasApplicationTests.java @@ -16,61 +16,54 @@ package smoketest.hateoas; -import java.util.Arrays; - import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleHateoasApplicationTests { @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @Test void hasHalLinksWhenAnythingIsAcceptable() { - HttpHeaders headers = new HttpHeaders(); - ResponseEntity<String> entity = this.restTemplate.exchange("/customers/1", HttpMethod.GET, - new HttpEntity<>(headers), String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).startsWith("{\"_links\":{\"self\":{\"href\""); - assertThat(entity.getBody()).endsWith(",\"id\":1,\"firstName\":\"Oliver\",\"lastName\":\"Gierke\"}"); + this.restTestClient.get().uri("/customers/1").exchangeSuccessfully().expectBody(String.class).value((body) -> { + assertThat(body).startsWith("{\"_links\":{\"self\":{\"href\""); + assertThat(body).endsWith(",\"id\":1,\"firstName\":\"Oliver\",\"lastName\":\"Gierke\"}"); + }); } @Test void hasHalLinksWhenJsonIsAcceptable() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); - ResponseEntity<String> entity = this.restTemplate.exchange("/customers/1", HttpMethod.GET, - new HttpEntity<>(headers), String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).startsWith("{\"_links\":{\"self\":{\"href\""); - assertThat(entity.getBody()).endsWith(",\"id\":1,\"firstName\":\"Oliver\",\"lastName\":\"Gierke\"}"); + this.restTestClient.get() + .uri("/customers/1") + .accept(MediaType.APPLICATION_JSON) + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> { + assertThat(body).startsWith("{\"_links\":{\"self\":{\"href\""); + assertThat(body).endsWith(",\"id\":1,\"firstName\":\"Oliver\",\"lastName\":\"Gierke\"}"); + }); } @Test void producesJsonWhenXmlIsPreferred() { - HttpHeaders headers = new HttpHeaders(); - headers.set(HttpHeaders.ACCEPT, "application/xml;q=0.9,application/json;q=0.8"); - HttpEntity<?> request = new HttpEntity<>(headers); - ResponseEntity<String> response = this.restTemplate.exchange("/customers/1", HttpMethod.GET, request, - String.class); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(response.getHeaders().getContentType()).isEqualTo(MediaType.parseMediaType("application/json")); + this.restTestClient.get() + .uri("/customers/1") + .header(HttpHeaders.ACCEPT, "application/xml;q=0.9,application/json;q=0.8") + .exchangeSuccessfully() + .expectHeader() + .contentType(MediaType.APPLICATION_JSON); } } diff --git a/smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/AbstractJerseyApplicationTests.java b/smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/AbstractJerseyApplicationTests.java index a881a351f58..4cb5fa7158b 100644 --- a/smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/AbstractJerseyApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/AbstractJerseyApplicationTests.java @@ -19,46 +19,55 @@ package smoketest.jersey; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.http.server.LocalTestWebServer; +import org.springframework.context.ApplicationContext; import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestClient; import static org.assertj.core.api.Assertions.assertThat; -@AutoConfigureTestRestTemplate @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "logging.level.root=debug") abstract class AbstractJerseyApplicationTests { + private final RestClient restClient = RestClient.create(); + @Autowired - private TestRestTemplate restTemplate; + private ApplicationContext applicationContext; @Test void contextLoads() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/hello", String.class); + ResponseEntity<String> entity = getForEntity("/hello"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test void reverse() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/reverse?input=olleh", String.class); + ResponseEntity<String> entity = getForEntity("/reverse?input=olleh"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("hello"); } @Test void validation() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/reverse", String.class); + ResponseEntity<String> entity = getForEntity("/reverse"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); } @Test void actuatorStatus() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/actuator/health", String.class); + ResponseEntity<String> entity = getForEntity("/actuator/health"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("{\"status\":\"UP\",\"groups\":[\"liveness\",\"readiness\"]}"); } + private ResponseEntity<String> getForEntity(String path) { + String uri = LocalTestWebServer.obtain(this.applicationContext).uri(path); + return this.restClient.get().uri(uri).retrieve().onStatus(HttpStatusCode::isError, (request, response) -> { + }).toEntity(String.class); + } + } diff --git a/smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/AbstractJerseyManagementPortTests.java b/smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/AbstractJerseyManagementPortTests.java index 9b131217bff..3b12e3b6e37 100644 --- a/smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/AbstractJerseyManagementPortTests.java +++ b/smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/AbstractJerseyManagementPortTests.java @@ -21,10 +21,7 @@ import jakarta.ws.rs.Path; import org.junit.jupiter.api.Test; import smoketest.jersey.AbstractJerseyManagementPortTests.ResourceConfigConfiguration; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.jersey.autoconfigure.ResourceConfigCustomizer; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.web.server.LocalManagementPort; @@ -32,7 +29,9 @@ import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Import; import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -42,49 +41,48 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -@AutoConfigureTestRestTemplate @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = "management.server.port=0") @Import(ResourceConfigConfiguration.class) class AbstractJerseyManagementPortTests { + private final RestClient restClient = RestClient.create(); + @LocalServerPort private int port; @LocalManagementPort private int managementPort; - @Autowired - private TestRestTemplate testRestTemplate; - @Test void resourceShouldBeAvailableOnMainPort() { - ResponseEntity<String> entity = this.testRestTemplate.getForEntity("http://localhost:" + this.port + "/test", - String.class); + ResponseEntity<String> entity = getForEntity("http://localhost:" + this.port + "/test"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("test"); } @Test void resourceShouldNotBeAvailableOnManagementPort() { - ResponseEntity<String> entity = this.testRestTemplate - .getForEntity("http://localhost:" + this.managementPort + "/test", String.class); + ResponseEntity<String> entity = getForEntity("http://localhost:" + this.managementPort + "/test"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @Test void actuatorShouldBeAvailableOnManagementPort() { - ResponseEntity<String> entity = this.testRestTemplate - .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); + ResponseEntity<String> entity = getForEntity("http://localhost:" + this.managementPort + "/actuator/health"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test void actuatorShouldNotBeAvailableOnMainPort() { - ResponseEntity<String> entity = this.testRestTemplate - .getForEntity("http://localhost:" + this.port + "/actuator/health", String.class); + ResponseEntity<String> entity = getForEntity("http://localhost:" + this.port + "/actuator/health"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } + private ResponseEntity<String> getForEntity(String uri) { + return this.restClient.get().uri(uri).retrieve().onStatus(HttpStatusCode::isError, (request, response) -> { + }).toEntity(String.class); + } + @TestConfiguration static class ResourceConfigConfiguration { diff --git a/smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyActuatorIsolatedObjectMapperFalseTests.java b/smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyActuatorIsolatedObjectMapperFalseTests.java index 284bda04a4a..d4ec7be37b5 100644 --- a/smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyActuatorIsolatedObjectMapperFalseTests.java +++ b/smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyActuatorIsolatedObjectMapperFalseTests.java @@ -19,16 +19,15 @@ package smoketest.jersey; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalManagementPort; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; import org.springframework.test.context.ContextConfiguration; +import org.springframework.web.client.RestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -37,7 +36,6 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -@AutoConfigureTestRestTemplate @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "management.endpoints.jackson2.isolated-object-mapper=false") @ContextConfiguration(loader = ApplicationStartupSpringBootContextLoader.class) @@ -49,13 +47,15 @@ class JerseyActuatorIsolatedObjectMapperFalseTests { @LocalManagementPort private int managementPort; - @Autowired - private TestRestTemplate testRestTemplate; - @Test void resourceShouldBeAvailableOnMainPort() { - ResponseEntity<String> entity = this.testRestTemplate - .getForEntity("http://localhost:" + this.port + "/actuator/startup", String.class); + ResponseEntity<String> entity = RestClient.create() + .get() + .uri("http://localhost:" + this.port + "/actuator/startup") + .retrieve() + .onStatus(HttpStatusCode::isError, (request, response) -> { + }) + .toEntity(String.class); System.out.println(entity.getBody()); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); assertThat(entity.getBody()) diff --git a/smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyActuatorIsolatedObjectMapperTrueTests.java b/smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyActuatorIsolatedObjectMapperTrueTests.java index bf71e1a4dd4..03397d4dc3e 100644 --- a/smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyActuatorIsolatedObjectMapperTrueTests.java +++ b/smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyActuatorIsolatedObjectMapperTrueTests.java @@ -19,9 +19,6 @@ package smoketest.jersey; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalManagementPort; @@ -29,6 +26,7 @@ import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.ContextConfiguration; +import org.springframework.web.client.RestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -37,7 +35,6 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -@AutoConfigureTestRestTemplate @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "management.endpoints.jackson.isolated-json-mapper=true") @ContextConfiguration(loader = ApplicationStartupSpringBootContextLoader.class) @@ -49,13 +46,13 @@ class JerseyActuatorIsolatedObjectMapperTrueTests { @LocalManagementPort private int managementPort; - @Autowired - private TestRestTemplate testRestTemplate; - @Test void resourceShouldBeAvailableOnMainPort() { - ResponseEntity<String> entity = this.testRestTemplate - .getForEntity("http://localhost:" + this.port + "/actuator/startup", String.class); + ResponseEntity<String> entity = RestClient.create() + .get() + .uri("http://localhost:" + this.port + "/actuator/startup") + .retrieve() + .toEntity(String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"timeline\":"); } diff --git a/smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyApplicationPathAndManagementPortTests.java b/smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyApplicationPathAndManagementPortTests.java index c56376ec69d..e00a08e649e 100644 --- a/smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyApplicationPathAndManagementPortTests.java +++ b/smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyApplicationPathAndManagementPortTests.java @@ -18,14 +18,12 @@ package smoketest.jersey; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalManagementPort; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -35,7 +33,6 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -@AutoConfigureTestRestTemplate @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { "management.server.port=0", "spring.jersey.application-path=/app" }) class JerseyApplicationPathAndManagementPortTests { @@ -46,13 +43,13 @@ class JerseyApplicationPathAndManagementPortTests { @LocalManagementPort private int managementPort; - @Autowired - private TestRestTemplate testRestTemplate; - @Test void applicationPathShouldNotAffectActuators() { - ResponseEntity<String> entity = this.testRestTemplate - .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); + ResponseEntity<String> entity = RestClient.create() + .get() + .uri("http://localhost:" + this.managementPort + "/actuator/health") + .retrieve() + .toEntity(String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } diff --git a/smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyDifferentPortSampleActuatorApplicationTests.java b/smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyDifferentPortSampleActuatorApplicationTests.java index b27538dfb06..f1640da2605 100644 --- a/smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyDifferentPortSampleActuatorApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyDifferentPortSampleActuatorApplicationTests.java @@ -18,11 +18,11 @@ package smoketest.jersey; import org.junit.jupiter.api.Test; -import org.springframework.boot.resttestclient.TestRestTemplate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalManagementPort; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -41,8 +41,12 @@ class JerseyDifferentPortSampleActuatorApplicationTests { @Test void linksEndpointShouldBeAvailable() { - ResponseEntity<String> entity = new TestRestTemplate("user", getPassword()) - .getForEntity("http://localhost:" + this.managementPort + "/", String.class); + ResponseEntity<String> entity = RestClient.create() + .get() + .uri("http://localhost:" + this.managementPort + "/") + .headers((headers) -> headers.setBasicAuth("user", getPassword())) + .retrieve() + .toEntity(String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"_links\""); } diff --git a/smoke-test/spring-boot-smoke-test-jetty-jsp/src/test/java/smoketest/jetty/jsp/SampleWebJspApplicationTests.java b/smoke-test/spring-boot-smoke-test-jetty-jsp/src/test/java/smoketest/jetty/jsp/SampleWebJspApplicationTests.java index eac7b377167..9be5c6f29e2 100644 --- a/smoke-test/spring-boot-smoke-test-jetty-jsp/src/test/java/smoketest/jetty/jsp/SampleWebJspApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-jetty-jsp/src/test/java/smoketest/jetty/jsp/SampleWebJspApplicationTests.java @@ -19,12 +19,10 @@ package smoketest.jetty.jsp; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -34,17 +32,19 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleWebJspApplicationTests { @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @Test void testJspWithEl() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("/resources/text.txt"); + this.restTestClient.get() + .uri("/") + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("/resources/text.txt")); } } diff --git a/smoke-test/spring-boot-smoke-test-jetty-ssl/build.gradle b/smoke-test/spring-boot-smoke-test-jetty-ssl/build.gradle index 5e816259fca..a6e6864a6e2 100644 --- a/smoke-test/spring-boot-smoke-test-jetty-ssl/build.gradle +++ b/smoke-test/spring-boot-smoke-test-jetty-ssl/build.gradle @@ -27,7 +27,7 @@ dependencies { } testImplementation(project(":starter:spring-boot-starter-webmvc-test")) - testImplementation(project(":module:spring-boot-restclient")) + testImplementation(project(":module:spring-boot-resttestclient")) testRuntimeOnly("org.apache.httpcomponents.client5:httpclient5") } diff --git a/smoke-test/spring-boot-smoke-test-jetty-ssl/src/test/java/smoketest/jetty/ssl/SampleJettySslApplicationTests.java b/smoke-test/spring-boot-smoke-test-jetty-ssl/src/test/java/smoketest/jetty/ssl/SampleJettySslApplicationTests.java index f2dc93b176d..2c22ad3a6ae 100644 --- a/smoke-test/spring-boot-smoke-test-jetty-ssl/src/test/java/smoketest/jetty/ssl/SampleJettySslApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-jetty-ssl/src/test/java/smoketest/jetty/ssl/SampleJettySslApplicationTests.java @@ -19,14 +19,13 @@ package smoketest.jetty.ssl; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.TrustAllTlsRequestFactory; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.boot.web.server.AbstractConfigurableWebServerFactory; import org.springframework.boot.web.server.Ssl; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -36,11 +35,10 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "debug=true") -@AutoConfigureTestRestTemplate class SampleJettySslApplicationTests { - @Autowired - private TestRestTemplate restTemplate; + @LocalServerPort + private int port; @Autowired private AbstractConfigurableWebServerFactory webServerFactory; @@ -54,9 +52,10 @@ class SampleJettySslApplicationTests { @Test void testHome() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).isEqualTo("Hello World"); + RestTestClient client = RestTestClient.bindToServer(TrustAllTlsRequestFactory.create()) + .baseUrl("https://localhost:" + this.port) + .build(); + client.get().uri("/").exchangeSuccessfully().expectBody(String.class).isEqualTo("Hello World"); } } diff --git a/smoke-test/spring-boot-smoke-test-jetty/src/test/java/smoketest/jetty/SampleJettyApplicationTests.java b/smoke-test/spring-boot-smoke-test-jetty/src/test/java/smoketest/jetty/SampleJettyApplicationTests.java index 12bcd600dd0..c21b21dac82 100644 --- a/smoke-test/spring-boot-smoke-test-jetty/src/test/java/smoketest/jetty/SampleJettyApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-jetty/src/test/java/smoketest/jetty/SampleJettyApplicationTests.java @@ -21,17 +21,11 @@ import smoketest.jetty.util.StringUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; - -import static org.assertj.core.api.Assertions.assertThat; +import org.springframework.test.web.servlet.client.RestTestClient; /** * Basic integration tests for demo application. @@ -43,46 +37,46 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Moritz Halbritter */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleJettyApplicationTests { @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @Value("${server.max-http-request-header-size}") private int maxHttpRequestHeaderSize; @Test void testHome() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).isEqualTo("Hello World"); + this.restTestClient.get().uri("/").exchangeSuccessfully().expectBody(String.class).isEqualTo("Hello World"); } @Test void testCompression() { // Jetty HttpClient sends Accept-Encoding: gzip by default - ResponseEntity<String> entity = this.restTemplate.getForEntity("/", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).isEqualTo("Hello World"); + this.restTestClient.get().uri("/").exchangeSuccessfully().expectBody(String.class).isEqualTo("Hello World"); // Jetty HttpClient decodes gzip responses automatically and removes the // Content-Encoding header. We have to assume that the response was gzipped. } @Test void testMaxHttpResponseHeaderSize() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/max-http-response-header", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); + this.restTestClient.get() + .uri("/max-http-response-header") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); } @Test void testMaxHttpRequestHeaderSize() { String headerValue = StringUtil.repeat('A', this.maxHttpRequestHeaderSize + 1); - HttpHeaders headers = new HttpHeaders(); - headers.add("x-max-request-header", headerValue); - HttpEntity<?> httpEntity = new HttpEntity<>(headers); - ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, httpEntity, String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.REQUEST_HEADER_FIELDS_TOO_LARGE); + this.restTestClient.get() + .uri("/") + .headers((headers) -> headers.add("x-max-request-header", headerValue)) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.REQUEST_HEADER_FIELDS_TOO_LARGE); } } diff --git a/smoke-test/spring-boot-smoke-test-oauth2-authorization-server/src/test/java/smoketest/oauth2/server/SampleOAuth2AuthorizationServerApplicationTests.java b/smoke-test/spring-boot-smoke-test-oauth2-authorization-server/src/test/java/smoketest/oauth2/server/SampleOAuth2AuthorizationServerApplicationTests.java index 871fe483d21..243b55a2429 100644 --- a/smoke-test/spring-boot-smoke-test-oauth2-authorization-server/src/test/java/smoketest/oauth2/server/SampleOAuth2AuthorizationServerApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-oauth2-authorization-server/src/test/java/smoketest/oauth2/server/SampleOAuth2AuthorizationServerApplicationTests.java @@ -16,38 +16,35 @@ package smoketest.oauth2.server; -import java.net.URI; -import java.util.List; import java.util.Map; import java.util.Objects; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.http.client.ClientHttpRequestFactoryBuilder; +import org.springframework.boot.http.client.HttpClientSettings; import org.springframework.boot.http.client.HttpRedirects; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationServerMetadata; import org.springframework.security.oauth2.server.authorization.oidc.OidcProviderConfiguration; +import org.springframework.test.web.servlet.client.EntityExchangeResult; +import org.springframework.test.web.servlet.client.RestTestClient; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleOAuth2AuthorizationServerApplicationTests { private static final ParameterizedTypeReference<Map<String, Object>> MAP_TYPE_REFERENCE = new ParameterizedTypeReference<>() { @@ -57,14 +54,24 @@ class SampleOAuth2AuthorizationServerApplicationTests { private int port; @Autowired - private TestRestTemplate restTemplate; + private RestTestClient rest; + + private RestTestClient nonFollowingRedirect() { + return RestTestClient + .bindToServer(ClientHttpRequestFactoryBuilder.detect() + .build(HttpClientSettings.defaults().withRedirects(HttpRedirects.DONT_FOLLOW))) + .baseUrl("http://localhost:" + this.port) + .build(); + } @Test void openidConfigurationShouldAllowAccess() { - ResponseEntity<Map<String, Object>> entity = this.restTemplate.exchange("/.well-known/openid-configuration", - HttpMethod.GET, null, MAP_TYPE_REFERENCE); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - Map<String, Object> body = entity.getBody(); + EntityExchangeResult<Map<String, Object>> result = this.rest.get() + .uri("/.well-known/openid-configuration") + .exchange() + .returnResult(MAP_TYPE_REFERENCE); + assertThat(result.getStatus()).isEqualTo(HttpStatus.OK); + Map<String, Object> body = result.getResponseBody(); assertThat(body).isNotNull(); OidcProviderConfiguration config = OidcProviderConfiguration.withClaims(body).build(); assertThat(config.getIssuer()).hasToString("https://provider.com"); @@ -82,10 +89,12 @@ class SampleOAuth2AuthorizationServerApplicationTests { @Test void authServerMetadataShouldAllowAccess() { - ResponseEntity<Map<String, Object>> entity = this.restTemplate - .exchange("/.well-known/oauth-authorization-server", HttpMethod.GET, null, MAP_TYPE_REFERENCE); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - Map<String, Object> body = entity.getBody(); + EntityExchangeResult<Map<String, Object>> result = this.rest.get() + .uri("/.well-known/oauth-authorization-server") + .exchange() + .returnResult(MAP_TYPE_REFERENCE); + assertThat(result.getStatus()).isEqualTo(HttpStatus.OK); + Map<String, Object> body = result.getResponseBody(); assertThat(body).isNotNull(); OAuth2AuthorizationServerMetadata config = OAuth2AuthorizationServerMetadata.withClaims(body).build(); assertThat(config.getIssuer()).hasToString("https://provider.com"); @@ -101,26 +110,26 @@ class SampleOAuth2AuthorizationServerApplicationTests { @Test void anonymousShouldRedirectToLogin() { - ResponseEntity<String> entity = this.restTemplate.withRedirects(HttpRedirects.DONT_FOLLOW) - .getForEntity("/", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - assertThat(entity.getHeaders().getLocation()).isEqualTo(URI.create("http://localhost:" + this.port + "/login")); + RestTestClient.ResponseSpec response = nonFollowingRedirect().get().uri("/").exchange(); + response.expectStatus().isFound(); + response.expectHeader().location("http://localhost:" + this.port + "/login"); } @Test void validTokenRequestShouldReturnTokenResponse() { - HttpHeaders headers = new HttpHeaders(); - headers.setBasicAuth("messaging-client", "secret"); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, Object> body = new LinkedMultiValueMap<>(); body.add(OAuth2ParameterNames.CLIENT_ID, "messaging-client"); body.add(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.CLIENT_CREDENTIALS.getValue()); body.add(OAuth2ParameterNames.SCOPE, "message.read message.write"); - HttpEntity<Object> request = new HttpEntity<>(body, headers); - ResponseEntity<Map<String, Object>> entity = this.restTemplate.exchange("/token", HttpMethod.POST, request, - MAP_TYPE_REFERENCE); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - Map<String, Object> tokenResponse = Objects.requireNonNull(entity.getBody()); + EntityExchangeResult<Map<String, Object>> result = this.rest.post() + .uri("/token") + .contentType(MediaType.APPLICATION_FORM_URLENCODED) + .headers((headers) -> headers.setBasicAuth("messaging-client", "secret")) + .body(body) + .exchange() + .returnResult(MAP_TYPE_REFERENCE); + assertThat(result.getStatus()).isEqualTo(HttpStatus.OK); + Map<String, Object> tokenResponse = Objects.requireNonNull(result.getResponseBody()); assertThat(tokenResponse.get(OAuth2ParameterNames.ACCESS_TOKEN)).isNotNull(); assertThat(tokenResponse.get(OAuth2ParameterNames.EXPIRES_IN)).isNotNull(); assertThat(tokenResponse.get(OAuth2ParameterNames.SCOPE)).isEqualTo("message.read message.write"); @@ -130,47 +139,49 @@ class SampleOAuth2AuthorizationServerApplicationTests { @Test void anonymousTokenRequestShouldReturnUnauthorized() { - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, Object> body = new LinkedMultiValueMap<>(); body.add(OAuth2ParameterNames.CLIENT_ID, "messaging-client"); body.add(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.CLIENT_CREDENTIALS.getValue()); body.add(OAuth2ParameterNames.SCOPE, "message.read message.write"); - HttpEntity<Object> request = new HttpEntity<>(body, headers); - ResponseEntity<Map<String, Object>> entity = this.restTemplate.exchange("/token", HttpMethod.POST, request, - MAP_TYPE_REFERENCE); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + EntityExchangeResult<Map<String, Object>> result = this.rest.post() + .uri("/token") + .contentType(MediaType.APPLICATION_FORM_URLENCODED) + .body(body) + .exchange() + .returnResult(MAP_TYPE_REFERENCE); + assertThat(result.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void anonymousTokenRequestWithAcceptHeaderAllShouldReturnUnauthorized() { - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - headers.setAccept(List.of(MediaType.ALL)); MultiValueMap<String, Object> body = new LinkedMultiValueMap<>(); body.add(OAuth2ParameterNames.CLIENT_ID, "messaging-client"); body.add(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.CLIENT_CREDENTIALS.getValue()); body.add(OAuth2ParameterNames.SCOPE, "message.read message.write"); - HttpEntity<Object> request = new HttpEntity<>(body, headers); - ResponseEntity<Map<String, Object>> entity = this.restTemplate.exchange("/token", HttpMethod.POST, request, - MAP_TYPE_REFERENCE); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + EntityExchangeResult<Map<String, Object>> result = this.rest.post() + .uri("/token") + .contentType(MediaType.APPLICATION_FORM_URLENCODED) + .accept(MediaType.ALL) + .body(body) + .exchange() + .returnResult(MAP_TYPE_REFERENCE); + assertThat(result.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void anonymousTokenRequestWithAcceptHeaderTextHtmlShouldRedirectToLogin() { - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - headers.setAccept(List.of(MediaType.TEXT_HTML)); MultiValueMap<String, Object> body = new LinkedMultiValueMap<>(); body.add(OAuth2ParameterNames.CLIENT_ID, "messaging-client"); body.add(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.CLIENT_CREDENTIALS.getValue()); body.add(OAuth2ParameterNames.SCOPE, "message.read message.write"); - HttpEntity<Object> request = new HttpEntity<>(body, headers); - ResponseEntity<Map<String, Object>> entity = this.restTemplate.withRedirects(HttpRedirects.DONT_FOLLOW) - .exchange("/token", HttpMethod.POST, request, MAP_TYPE_REFERENCE); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - assertThat(entity.getHeaders().getLocation()).isEqualTo(URI.create("http://localhost:" + this.port + "/login")); + RestTestClient.ResponseSpec response = nonFollowingRedirect().post() + .uri("/token") + .contentType(MediaType.APPLICATION_FORM_URLENCODED) + .accept(MediaType.TEXT_HTML) + .body(body) + .exchange(); + response.expectStatus().isFound(); + response.expectHeader().location("http://localhost:" + this.port + "/login"); } } diff --git a/smoke-test/spring-boot-smoke-test-oauth2-client/src/test/java/smoketest/oauth2/client/SampleOAuth2ClientApplicationTests.java b/smoke-test/spring-boot-smoke-test-oauth2-client/src/test/java/smoketest/oauth2/client/SampleOAuth2ClientApplicationTests.java index 64c268c62a9..63e68d23806 100644 --- a/smoke-test/spring-boot-smoke-test-oauth2-client/src/test/java/smoketest/oauth2/client/SampleOAuth2ClientApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-oauth2-client/src/test/java/smoketest/oauth2/client/SampleOAuth2ClientApplicationTests.java @@ -16,49 +16,56 @@ package smoketest.oauth2.client; -import java.net.URI; - import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.http.client.ClientHttpRequestFactoryBuilder; +import org.springframework.boot.http.client.HttpClientSettings; import org.springframework.boot.http.client.HttpRedirects; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { "APP-CLIENT-ID=my-client-id", "APP-CLIENT-SECRET=my-client-secret", "YAHOO-CLIENT-ID=my-yahoo-client-id", "YAHOO-CLIENT-SECRET=my-yahoo-client-secret" }) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleOAuth2ClientApplicationTests { @LocalServerPort private int port; @Autowired - private TestRestTemplate restTemplate; + private RestTestClient rest; + + private RestTestClient nonFollowingRedirect() { + return RestTestClient + .bindToServer(ClientHttpRequestFactoryBuilder.detect() + .build(HttpClientSettings.defaults().withRedirects(HttpRedirects.DONT_FOLLOW))) + .baseUrl("http://localhost:" + this.port) + .build(); + } @Test void everythingShouldRedirectToLogin() { - ResponseEntity<String> entity = this.restTemplate.withRedirects(HttpRedirects.DONT_FOLLOW) - .getForEntity("/", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - assertThat(entity.getHeaders().getLocation()).isEqualTo(URI.create("http://localhost:" + this.port + "/login")); + RestTestClient.ResponseSpec response = nonFollowingRedirect().get().uri("/").exchange(); + response.expectStatus().isFound(); + response.expectHeader().location("http://localhost:" + this.port + "/login"); } @Test void loginShouldHaveAllOAuth2ClientsToChooseFrom() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/login", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("/oauth2/authorization/yahoo"); - assertThat(entity.getBody()).contains("/oauth2/authorization/github-client-1"); - assertThat(entity.getBody()).contains("/oauth2/authorization/github-client-2"); - assertThat(entity.getBody()).contains("/oauth2/authorization/github-repos"); + this.rest.get() + .uri("/login") + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("/oauth2/authorization/yahoo") + .contains("/oauth2/authorization/github-client-1") + .contains("/oauth2/authorization/github-client-2") + .contains("/oauth2/authorization/github-repos")); } } diff --git a/smoke-test/spring-boot-smoke-test-oauth2-resource-server/src/test/java/smoketest/oauth2/resource/SampleOauth2ResourceServerApplicationTests.java b/smoke-test/spring-boot-smoke-test-oauth2-resource-server/src/test/java/smoketest/oauth2/resource/SampleOauth2ResourceServerApplicationTests.java index bb4b93c88c5..eb56c2439d8 100644 --- a/smoke-test/spring-boot-smoke-test-oauth2-resource-server/src/test/java/smoketest/oauth2/resource/SampleOauth2ResourceServerApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-oauth2-resource-server/src/test/java/smoketest/oauth2/resource/SampleOauth2ResourceServerApplicationTests.java @@ -25,20 +25,14 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; - -import static org.assertj.core.api.Assertions.assertThat; +import org.springframework.test.web.servlet.client.RestTestClient; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleOauth2ResourceServerApplicationTests { private static final MockWebServer server = new MockWebServer(); @@ -50,7 +44,7 @@ class SampleOauth2ResourceServerApplicationTests { + "R44vmRqS5ncrF-1R0EGcPX49U6A"; @Autowired - private TestRestTemplate restTemplate; + private RestTestClient rest; @BeforeAll static void setup() throws Exception { @@ -68,19 +62,17 @@ class SampleOauth2ResourceServerApplicationTests { @Test void withValidBearerTokenShouldAllowAccess() { - HttpHeaders headers = new HttpHeaders(); - headers.setBearerAuth(VALID_TOKEN); - HttpEntity<?> request = new HttpEntity<Void>(headers); - ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, request, String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + this.rest.get() + .uri("/") + .headers((headers) -> headers.setBearerAuth(VALID_TOKEN)) + .exchange() + .expectStatus() + .isOk(); } @Test void withNoBearerTokenShouldNotAllowAccess() { - HttpHeaders headers = new HttpHeaders(); - HttpEntity<?> request = new HttpEntity<Void>(headers); - ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, request, String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + this.rest.get().uri("/").exchange().expectStatus().isUnauthorized(); } private static MockResponse mockResponse() { diff --git a/smoke-test/spring-boot-smoke-test-prometheus/src/test/java/smoketest/prometheus/SamplePrometheusApplicationTests.java b/smoke-test/spring-boot-smoke-test-prometheus/src/test/java/smoketest/prometheus/SamplePrometheusApplicationTests.java index ca615561db2..5b5f158cede 100644 --- a/smoke-test/spring-boot-smoke-test-prometheus/src/test/java/smoketest/prometheus/SamplePrometheusApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-prometheus/src/test/java/smoketest/prometheus/SamplePrometheusApplicationTests.java @@ -20,15 +20,13 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.micrometer.metrics.test.autoconfigure.AutoConfigureMetrics; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.http.HttpEntity; +import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -39,22 +37,26 @@ import static org.assertj.core.api.Assertions.assertThat; */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @AutoConfigureMetrics -@AutoConfigureTestRestTemplate class SamplePrometheusApplicationTests { @Autowired - private TestRestTemplate restTemplate; + private RestClient.Builder restClientBuilder; + + @LocalServerPort + private int port; @Test void shouldExportExemplars() { + RestClient restClient = this.restClientBuilder.baseUrl("http://localhost:" + this.port).build(); for (int i = 0; i < 10; i++) { - ResponseEntity<String> response = this.restTemplate.getForEntity("/actuator", String.class); + ResponseEntity<Void> response = restClient.get().uri("/actuator").retrieve().toBodilessEntity(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); } - HttpHeaders headers = new HttpHeaders(); - headers.add(HttpHeaders.ACCEPT, "application/openmetrics-text; version=1.0.0; charset=utf-8"); - ResponseEntity<String> metrics = this.restTemplate.exchange("/actuator/prometheus", HttpMethod.GET, - new HttpEntity<>(headers), String.class); + ResponseEntity<String> metrics = restClient.get() + .uri("/actuator/prometheus") + .header(HttpHeaders.ACCEPT, "application/openmetrics-text; version=1.0.0; charset=utf-8") + .retrieve() + .toEntity(String.class); assertThat(metrics.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(metrics.getBody()).containsSubsequence("http_client_requests_seconds_count", "span_id", "trace_id"); } diff --git a/smoke-test/spring-boot-smoke-test-quartz/src/test/java/smoketest/quartz/SampleQuartzApplicationWebTests.java b/smoke-test/spring-boot-smoke-test-quartz/src/test/java/smoketest/quartz/SampleQuartzApplicationWebTests.java index 956b28e92be..7a3e960299c 100644 --- a/smoke-test/spring-boot-smoke-test-quartz/src/test/java/smoketest/quartz/SampleQuartzApplicationWebTests.java +++ b/smoke-test/spring-boot-smoke-test-quartz/src/test/java/smoketest/quartz/SampleQuartzApplicationWebTests.java @@ -25,20 +25,18 @@ import org.assertj.core.api.InstanceOfAssertFactories; import org.assertj.core.api.InstanceOfAssertFactory; import org.assertj.core.api.MapAssert; import org.awaitility.Awaitility; -import org.jspecify.annotations.Nullable; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.system.CapturedOutput; import org.springframework.boot.test.system.OutputCaptureExtension; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.test.web.servlet.client.RestTestClient; +import org.springframework.test.web.servlet.client.RestTestClient.BodySpec; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; @@ -51,84 +49,88 @@ import static org.assertj.core.api.Assertions.within; */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @ExtendWith(OutputCaptureExtension.class) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleQuartzApplicationWebTests { + private static final ParameterizedTypeReference<Map<String, Object>> MAP_TYPE = new ParameterizedTypeReference<>() { + }; + @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @Test void quartzGroupNames() { - Map<String, Object> content = getContent("/actuator/quartz"); - assertThat(content).containsOnlyKeys("jobs", "triggers"); + assertContent("/actuator/quartz").value((content) -> assertThat(content).containsOnlyKeys("jobs", "triggers")); } @Test void quartzJobGroups() { - Map<String, Object> content = getContent("/actuator/quartz/jobs"); - assertThat(content).containsOnlyKeys("groups"); - assertThat(content).extractingByKey("groups", nestedMap()).containsOnlyKeys("samples"); + assertContent("/actuator/quartz/jobs").value((content) -> { + assertThat(content).containsOnlyKeys("groups"); + assertThat(content).extractingByKey("groups", nestedMap()).containsOnlyKeys("samples"); + }); } @Test void quartzTriggerGroups() { - Map<String, Object> content = getContent("/actuator/quartz/triggers"); - assertThat(content).containsOnlyKeys("groups"); - assertThat(content).extractingByKey("groups", nestedMap()).containsOnlyKeys("DEFAULT", "samples"); + assertContent("/actuator/quartz/triggers").value((content) -> { + assertThat(content).containsOnlyKeys("groups"); + assertThat(content).extractingByKey("groups", nestedMap()).containsOnlyKeys("DEFAULT", "samples"); + }); } @Test void quartzJobDetail() { - Map<String, Object> content = getContent("/actuator/quartz/jobs/samples/helloJob"); - assertThat(content).containsEntry("name", "helloJob").containsEntry("group", "samples"); + assertContent("/actuator/quartz/jobs/samples/helloJob").value( + (content) -> assertThat(content).containsEntry("name", "helloJob").containsEntry("group", "samples")); } @Test void quartzJobDetailWhenNameDoesNotExistReturns404() { - ResponseEntity<String> response = this.restTemplate.getForEntity("/actuator/quartz/jobs/samples/does-not-exist", - String.class); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + this.restTestClient.get() + .uri("/actuator/quartz/jobs/samples/does-not-exist") + .exchange() + .expectStatus() + .isNotFound(); } @Test void quartzTriggerDetail() { - Map<String, Object> content = getContent("/actuator/quartz/triggers/samples/3am-weekdays"); - assertThat(content).contains(entry("group", "samples"), entry("name", "3am-weekdays"), entry("state", "NORMAL"), - entry("type", "cron")); + assertContent("/actuator/quartz/triggers/samples/3am-weekdays") + .value((content) -> assertThat(content).contains(entry("group", "samples"), entry("name", "3am-weekdays"), + entry("state", "NORMAL"), entry("type", "cron"))); } @Test void quartzTriggerDetailWhenNameDoesNotExistReturns404() { - ResponseEntity<String> response = this.restTemplate - .getForEntity("/actuator/quartz/triggers/samples/does-not-exist", String.class); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + this.restTestClient.get() + .uri("/actuator/quartz/triggers/samples/does-not-exist") + .exchange() + .expectStatus() + .isNotFound(); } @Test void quartzJobTriggeredManually(CapturedOutput output) { - ResponseEntity<Map<String, Object>> result = asMapEntity(this.restTemplate.postForEntity( - "/actuator/quartz/jobs/samples/onDemandJob", new HttpEntity<>(Map.of("state", "running")), Map.class)); - assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); - Map<String, Object> content = result.getBody(); - assertThat(content).contains(entry("group", "samples"), entry("name", "onDemandJob"), - entry("className", SampleJob.class.getName())); - assertThat(content).extractingByKey("triggerTime", InstanceOfAssertFactories.STRING) - .satisfies((triggerTime) -> assertThat(Instant.parse(triggerTime)).isCloseTo(Instant.now(), - within(10, ChronoUnit.SECONDS))); + this.restTestClient.post() + .uri("/actuator/quartz/jobs/samples/onDemandJob") + .body(Map.of("state", "running")) + .exchangeSuccessfully() + .expectBody(MAP_TYPE) + .value((content) -> { + assertThat(content).contains(entry("group", "samples"), entry("name", "onDemandJob"), + entry("className", SampleJob.class.getName())); + assertThat(content).extractingByKey("triggerTime", InstanceOfAssertFactories.STRING) + .satisfies((triggerTime) -> assertThat(Instant.parse(triggerTime)).isCloseTo(Instant.now(), + within(10, ChronoUnit.SECONDS))); + }); Awaitility.await() .atMost(Duration.ofSeconds(30)) .untilAsserted(() -> assertThat(output).contains("Hello On Demand Job")); } - private @Nullable Map<String, Object> getContent(String path) { - ResponseEntity<Map<String, Object>> entity = asMapEntity(this.restTemplate.getForEntity(path, Map.class)); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - return entity.getBody(); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - private static <K, V> ResponseEntity<Map<K, V>> asMapEntity(ResponseEntity<Map> entity) { - return (ResponseEntity) entity; + private BodySpec<Map<String, Object>, ?> assertContent(String path) { + return this.restTestClient.get().uri(path).exchangeSuccessfully().expectBody(MAP_TYPE); } @SuppressWarnings("rawtypes") diff --git a/smoke-test/spring-boot-smoke-test-saml2-service-provider/src/test/java/smoketest/saml2/serviceprovider/SampleSaml2RelyingPartyApplicationTests.java b/smoke-test/spring-boot-smoke-test-saml2-service-provider/src/test/java/smoketest/saml2/serviceprovider/SampleSaml2RelyingPartyApplicationTests.java index 1123740a024..e3e130bfbb9 100644 --- a/smoke-test/spring-boot-smoke-test-saml2-service-provider/src/test/java/smoketest/saml2/serviceprovider/SampleSaml2RelyingPartyApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-saml2-service-provider/src/test/java/smoketest/saml2/serviceprovider/SampleSaml2RelyingPartyApplicationTests.java @@ -16,45 +16,52 @@ package smoketest.saml2.serviceprovider; -import java.net.URI; - import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.http.client.ClientHttpRequestFactoryBuilder; +import org.springframework.boot.http.client.HttpClientSettings; import org.springframework.boot.http.client.HttpRedirects; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleSaml2RelyingPartyApplicationTests { @LocalServerPort private int port; @Autowired - private TestRestTemplate restTemplate; + private RestTestClient rest; + + private RestTestClient nonFollowingRedirect() { + return RestTestClient + .bindToServer(ClientHttpRequestFactoryBuilder.detect() + .build(HttpClientSettings.defaults().withRedirects(HttpRedirects.DONT_FOLLOW))) + .baseUrl("http://localhost:" + this.port) + .build(); + } @Test void everythingShouldRedirectToLogin() { - ResponseEntity<String> entity = this.restTemplate.withRedirects(HttpRedirects.DONT_FOLLOW) - .getForEntity("/", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - assertThat(entity.getHeaders().getLocation()).isEqualTo(URI.create("http://localhost:" + this.port + "/login")); + RestTestClient.ResponseSpec response = nonFollowingRedirect().get().uri("/").exchange(); + response.expectStatus().isFound(); + response.expectHeader().location("http://localhost:" + this.port + "/login"); } @Test void loginShouldHaveAllAssertingPartiesToChooseFrom() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/login", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("/saml2/authenticate?registrationId=simplesamlphp"); - assertThat(entity.getBody()).contains("/saml2/authenticate?registrationId=okta"); + this.rest.get() + .uri("/login") + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("/saml2/authenticate?registrationId=simplesamlphp") + .contains("/saml2/authenticate?registrationId=okta")); } } diff --git a/smoke-test/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/AbstractJerseySecureTests.java b/smoke-test/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/AbstractJerseySecureTests.java index 1c76932cdd7..a6aacc48115 100644 --- a/smoke-test/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/AbstractJerseySecureTests.java +++ b/smoke-test/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/AbstractJerseySecureTests.java @@ -18,11 +18,10 @@ package smoketest.secure.jersey; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -31,133 +30,126 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -@AutoConfigureTestRestTemplate abstract class AbstractJerseySecureTests { + private final RestClient restClient = RestClient.create(); + abstract String getPath(); abstract String getManagementPath(); - @Autowired - private TestRestTemplate testRestTemplate; - @Test void helloEndpointIsSecure() { - ResponseEntity<String> entity = restTemplate().getForEntity(getPath() + "/hello", String.class); + ResponseEntity<String> entity = getForEntity(restClient(), getPath() + "/hello"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void actuatorInsecureEndpoint() { - ResponseEntity<String> entity = restTemplate().getForEntity(getManagementPath() + "/actuator/health", - String.class); + ResponseEntity<String> entity = getForEntity(restClient(), getManagementPath() + "/actuator/health"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); - entity = restTemplate().getForEntity(getManagementPath() + "/actuator/health/diskSpace", String.class); + entity = getForEntity(restClient(), getManagementPath() + "/actuator/health/diskSpace"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } @Test void actuatorLinksWithAnonymous() { - ResponseEntity<String> entity = restTemplate().getForEntity(getManagementPath() + "/actuator", String.class); + ResponseEntity<String> entity = getForEntity(restClient(), getManagementPath() + "/actuator"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); - entity = restTemplate().getForEntity(getManagementPath() + "/actuator/", String.class); + entity = getForEntity(restClient(), getManagementPath() + "/actuator/"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void actuatorLinksWithUnauthorizedUser() { - ResponseEntity<String> entity = userRestTemplate().getForEntity(getManagementPath() + "/actuator", - String.class); + ResponseEntity<String> entity = getForEntity(userRestClient(), getManagementPath() + "/actuator"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); - entity = userRestTemplate().getForEntity(getManagementPath() + "/actuator/", String.class); + entity = getForEntity(userRestClient(), getManagementPath() + "/actuator/"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } @Test void actuatorLinksWithAuthorizedUser() { - ResponseEntity<String> entity = adminRestTemplate().getForEntity(getManagementPath() + "/actuator", - String.class); + ResponseEntity<String> entity = getForEntity(adminRestClient(), getManagementPath() + "/actuator"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - adminRestTemplate().getForEntity(getManagementPath() + "/actuator/", String.class); + getForEntity(adminRestClient(), getManagementPath() + "/actuator/"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test void actuatorSecureEndpointWithAnonymous() { - ResponseEntity<String> entity = restTemplate().getForEntity(getManagementPath() + "/actuator/env", - String.class); + ResponseEntity<String> entity = getForEntity(restClient(), getManagementPath() + "/actuator/env"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); - entity = restTemplate().getForEntity( - getManagementPath() + "/actuator/env/management.endpoints.web.exposure.include", String.class); + entity = getForEntity(restClient(), + getManagementPath() + "/actuator/env/management.endpoints.web.exposure.include"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void actuatorSecureEndpointWithUnauthorizedUser() { - ResponseEntity<String> entity = userRestTemplate().getForEntity(getManagementPath() + "/actuator/env", - String.class); + ResponseEntity<String> entity = getForEntity(userRestClient(), getManagementPath() + "/actuator/env"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); - entity = userRestTemplate().getForEntity( - getManagementPath() + "/actuator/env/management.endpoints.web.exposure.include", String.class); + entity = getForEntity(userRestClient(), + getManagementPath() + "/actuator/env/management.endpoints.web.exposure.include"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } @Test void actuatorSecureEndpointWithAuthorizedUser() { - ResponseEntity<String> entity = adminRestTemplate().getForEntity(getManagementPath() + "/actuator/env", - String.class); + ResponseEntity<String> entity = getForEntity(adminRestClient(), getManagementPath() + "/actuator/env"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - entity = adminRestTemplate().getForEntity( - getManagementPath() + "/actuator/env/management.endpoints.web.exposure.include", String.class); + entity = getForEntity(adminRestClient(), + getManagementPath() + "/actuator/env/management.endpoints.web.exposure.include"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test void secureServletEndpointWithAnonymous() { - ResponseEntity<String> entity = restTemplate().getForEntity(getManagementPath() + "/actuator/se1", - String.class); + ResponseEntity<String> entity = getForEntity(restClient(), getManagementPath() + "/actuator/se1"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); - entity = restTemplate().getForEntity(getManagementPath() + "/actuator/se1/list", String.class); + entity = getForEntity(restClient(), getManagementPath() + "/actuator/se1/list"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void secureServletEndpointWithUnauthorizedUser() { - ResponseEntity<String> entity = userRestTemplate().getForEntity(getManagementPath() + "/actuator/se1", - String.class); + ResponseEntity<String> entity = getForEntity(userRestClient(), getManagementPath() + "/actuator/se1"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); - entity = userRestTemplate().getForEntity(getManagementPath() + "/actuator/se1/list", String.class); + entity = getForEntity(userRestClient(), getManagementPath() + "/actuator/se1/list"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } @Test void secureServletEndpointWithAuthorizedUser() { - ResponseEntity<String> entity = adminRestTemplate().getForEntity(getManagementPath() + "/actuator/se1", - String.class); + ResponseEntity<String> entity = getForEntity(adminRestClient(), getManagementPath() + "/actuator/se1"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - entity = adminRestTemplate().getForEntity(getManagementPath() + "/actuator/se1/list", String.class); + entity = getForEntity(adminRestClient(), getManagementPath() + "/actuator/se1/list"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test void actuatorExcludedFromEndpointRequestMatcher() { - ResponseEntity<String> entity = userRestTemplate().getForEntity(getManagementPath() + "/actuator/mappings", - String.class); + ResponseEntity<String> entity = getForEntity(userRestClient(), getManagementPath() + "/actuator/mappings"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } - TestRestTemplate restTemplate() { - return this.testRestTemplate; + RestClient restClient() { + return this.restClient; } - TestRestTemplate adminRestTemplate() { - return this.testRestTemplate.withBasicAuth("admin", "admin"); + RestClient adminRestClient() { + return RestClient.builder().defaultHeaders((headers) -> headers.setBasicAuth("admin", "admin")).build(); } - TestRestTemplate userRestTemplate() { - return this.testRestTemplate.withBasicAuth("user", "password"); + RestClient userRestClient() { + return RestClient.builder().defaultHeaders((headers) -> headers.setBasicAuth("user", "password")).build(); + } + + static ResponseEntity<String> getForEntity(RestClient client, String uri) { + return client.get().uri(uri).retrieve().onStatus(HttpStatusCode::isError, (request, response) -> { + }).toEntity(String.class); } } diff --git a/smoke-test/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/ManagementPortAndPathJerseyApplicationTests.java b/smoke-test/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/ManagementPortAndPathJerseyApplicationTests.java index 1641ab8f8f2..448add3e653 100644 --- a/smoke-test/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/ManagementPortAndPathJerseyApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/ManagementPortAndPathJerseyApplicationTests.java @@ -18,7 +18,6 @@ package smoketest.secure.jersey; import org.junit.jupiter.api.Test; -import org.springframework.boot.resttestclient.TestRestTemplate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalManagementPort; @@ -47,8 +46,8 @@ class ManagementPortAndPathJerseyApplicationTests extends AbstractJerseySecureTe @Test void testMissing() { - ResponseEntity<String> entity = new TestRestTemplate("admin", "admin") - .getForEntity("http://localhost:" + this.managementPort + "/management/actuator/missing", String.class); + ResponseEntity<String> entity = getForEntity(adminRestClient(), + "http://localhost:" + this.managementPort + "/management/actuator/missing"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } diff --git a/smoke-test/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/ManagementPortCustomApplicationPathJerseyTests.java b/smoke-test/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/ManagementPortCustomApplicationPathJerseyTests.java index 84442ce9097..e1d6d58d0e7 100644 --- a/smoke-test/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/ManagementPortCustomApplicationPathJerseyTests.java +++ b/smoke-test/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/ManagementPortCustomApplicationPathJerseyTests.java @@ -18,7 +18,6 @@ package smoketest.secure.jersey; import org.junit.jupiter.api.Test; -import org.springframework.boot.resttestclient.TestRestTemplate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalManagementPort; import org.springframework.boot.test.web.server.LocalServerPort; @@ -45,8 +44,8 @@ class ManagementPortCustomApplicationPathJerseyTests extends AbstractJerseySecur @Test void actuatorPathOnMainPortShouldNotMatch() { - ResponseEntity<String> entity = new TestRestTemplate() - .getForEntity("http://localhost:" + this.port + "/example/actuator/health", String.class); + ResponseEntity<String> entity = getForEntity(restClient(), + "http://localhost:" + this.port + "/example/actuator/health"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } diff --git a/smoke-test/spring-boot-smoke-test-servlet/build.gradle b/smoke-test/spring-boot-smoke-test-servlet/build.gradle index fc5cf715f79..694e486ba8c 100644 --- a/smoke-test/spring-boot-smoke-test-servlet/build.gradle +++ b/smoke-test/spring-boot-smoke-test-servlet/build.gradle @@ -26,7 +26,6 @@ dependencies { implementation(project(":starter:spring-boot-starter-security")) testImplementation(project(":module:spring-boot-restclient")) - testImplementation(project(":module:spring-boot-resttestclient")) testImplementation(project(":starter:spring-boot-starter-test")) testRuntimeOnly(project(":starter:spring-boot-starter-tomcat")) diff --git a/smoke-test/spring-boot-smoke-test-servlet/src/test/java/smoketest/servlet/SampleServletApplicationTests.java b/smoke-test/spring-boot-smoke-test-servlet/src/test/java/smoketest/servlet/SampleServletApplicationTests.java index 4cb9d124a75..7043e8c1909 100644 --- a/smoke-test/spring-boot-smoke-test-servlet/src/test/java/smoketest/servlet/SampleServletApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-servlet/src/test/java/smoketest/servlet/SampleServletApplicationTests.java @@ -16,21 +16,16 @@ package smoketest.servlet; -import java.util.Collections; - import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; +import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -40,29 +35,35 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -@AutoConfigureTestRestTemplate class SampleServletApplicationTests { - @Autowired - private TestRestTemplate restTemplate; + @LocalServerPort + private int port; @Test void testHomeIsSecure() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); - ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, new HttpEntity<>(headers), - String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + HttpStatusCode status = restClient().get() + .uri("/") + .accept(MediaType.APPLICATION_JSON) + .exchange((request, response) -> response.getStatusCode()); + assertThat(status).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void testHome() { - ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()) - .getForEntity("/", String.class); + ResponseEntity<String> entity = restClient().get() + .uri("/") + .headers((headers) -> headers.setBasicAuth("user", getPassword())) + .retrieve() + .toEntity(String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("Hello World"); } + private RestClient restClient() { + return RestClient.create("http://localhost:" + this.port); + } + private String getPassword() { return "password"; } diff --git a/smoke-test/spring-boot-smoke-test-session-data-redis/src/dockerTest/java/smoketest/session/redis/SampleSessionRedisApplicationTests.java b/smoke-test/spring-boot-smoke-test-session-data-redis/src/dockerTest/java/smoketest/session/redis/SampleSessionRedisApplicationTests.java index 8357eea38cf..7d3da8cac43 100644 --- a/smoke-test/spring-boot-smoke-test-session-data-redis/src/dockerTest/java/smoketest/session/redis/SampleSessionRedisApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-session-data-redis/src/dockerTest/java/smoketest/session/redis/SampleSessionRedisApplicationTests.java @@ -16,8 +16,6 @@ package smoketest.session.redis; -import java.net.URI; -import java.util.Collections; import java.util.List; import java.util.Map; @@ -27,19 +25,14 @@ import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.testcontainers.service.connection.ServiceConnection; import org.springframework.boot.testsupport.container.TestImage; import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.RequestEntity; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.EntityExchangeResult; +import org.springframework.test.web.servlet.client.RestTestClient; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; @@ -55,7 +48,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @Testcontainers(disabledWithoutDocker = true) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleSessionRedisApplicationTests { @Container @@ -63,42 +56,39 @@ class SampleSessionRedisApplicationTests { static RedisContainer redis = TestImage.container(RedisContainer.class); @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @Test @SuppressWarnings("unchecked") void sessionsEndpointShouldReturnUserSessions() { performLogin(); - ResponseEntity<Map<String, Object>> response = getSessions(); - assertThat(response).isNotNull(); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); - Map<String, Object> body = response.getBody(); + Map<String, Object> body = getSessions().getResponseBody(); assertThat(body).isNotNull(); List<Map<String, Object>> sessions = (List<Map<String, Object>>) body.get("sessions"); assertThat(sessions).hasSize(1); } private void performLogin() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Collections.singletonList(MediaType.TEXT_HTML)); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.set("username", "user"); form.set("password", "password"); - this.restTemplate.exchange("/login", HttpMethod.POST, new HttpEntity<>(form, headers), String.class); + this.restTestClient.post() + .uri("/login") + .accept(MediaType.TEXT_HTML) + .contentType(MediaType.APPLICATION_FORM_URLENCODED) + .body(form) + .exchange(); } - private RequestEntity<Object> getRequestEntity(URI uri) { - HttpHeaders headers = new HttpHeaders(); - headers.setBasicAuth("user", "password"); - return new RequestEntity<>(headers, HttpMethod.GET, uri); - } - - private ResponseEntity<Map<String, Object>> getSessions() { - RequestEntity<Object> request = getRequestEntity(URI.create("/actuator/sessions?username=user")); + private EntityExchangeResult<Map<String, Object>> getSessions() { ParameterizedTypeReference<Map<String, Object>> stringObjectMap = new ParameterizedTypeReference<>() { }; - return this.restTemplate.exchange(request, stringObjectMap); + return this.restTestClient.get() + .uri("/actuator/sessions?username=user") + .headers((headers) -> headers.setBasicAuth("user", "password")) + .exchangeSuccessfully() + .expectBody(stringObjectMap) + .returnResult(); } } diff --git a/smoke-test/spring-boot-smoke-test-session-jdbc/src/test/java/smoketest/session/SampleSessionJdbcApplicationTests.java b/smoke-test/spring-boot-smoke-test-session-jdbc/src/test/java/smoketest/session/SampleSessionJdbcApplicationTests.java index bf669174b17..989bc47f24a 100644 --- a/smoke-test/spring-boot-smoke-test-session-jdbc/src/test/java/smoketest/session/SampleSessionJdbcApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-session-jdbc/src/test/java/smoketest/session/SampleSessionJdbcApplicationTests.java @@ -28,18 +28,16 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.http.client.ClientHttpRequestFactoryBuilder; import org.springframework.boot.http.client.HttpClientSettings; import org.springframework.boot.http.client.HttpRedirects; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.http.client.ClientHttpRequestFactory; +import org.springframework.test.web.servlet.client.EntityExchangeResult; +import org.springframework.test.web.servlet.client.RestTestClient; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestClient; @@ -55,14 +53,14 @@ import static org.assertj.core.api.Assertions.assertThat; */ @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { "server.servlet.session.timeout:2", "debug=true" }) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleSessionJdbcApplicationTests { private static final HttpClientSettings DONT_FOLLOW_REDIRECTS = HttpClientSettings.defaults() .withRedirects(HttpRedirects.DONT_FOLLOW); @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @LocalServerPort @SuppressWarnings("NullAway.Init") @@ -70,14 +68,23 @@ class SampleSessionJdbcApplicationTests { private static final URI ROOT_URI = URI.create("/"); + /** + * A client that follows redirects, used to emulate a browser session. + */ + private RestTestClient browserClient() { + ClientHttpRequestFactory requestFactory = ClientHttpRequestFactoryBuilder.detect() + .build(HttpClientSettings.defaults()); + return RestTestClient.bindToServer(requestFactory).baseUrl("http://localhost:" + this.port).build(); + } + @Test void sessionExpiry() throws Exception { String cookie = performLogin(); - String sessionId1 = performRequest(ROOT_URI, cookie).getBody(); - String sessionId2 = performRequest(ROOT_URI, cookie).getBody(); + String sessionId1 = performRequest(ROOT_URI, cookie).getResponseBody(); + String sessionId2 = performRequest(ROOT_URI, cookie).getResponseBody(); assertThat(sessionId1).isEqualTo(sessionId2); Thread.sleep(2100); - String loginPage = performRequest(ROOT_URI, cookie).getBody(); + String loginPage = performRequest(ROOT_URI, cookie).getResponseBody(); assertThat(loginPage).containsIgnoringCase("login"); } @@ -101,19 +108,20 @@ class SampleSessionJdbcApplicationTests { @SuppressWarnings("unchecked") void sessionsEndpointShouldReturnUserSession() { performLogin(); - ResponseEntity<Map<String, Object>> response = getSessions(); - assertThat(response).isNotNull(); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); - Map<String, Object> body = response.getBody(); + Map<String, Object> body = getSessions().getResponseBody(); assertThat(body).isNotNull(); List<Map<String, Object>> sessions = (List<Map<String, Object>>) body.get("sessions"); assertThat(sessions).hasSize(1); } - private ResponseEntity<String> performRequest(URI uri, @Nullable String cookie) { - HttpHeaders headers = getHeaders(cookie); - RequestEntity<Object> request = new RequestEntity<>(headers, HttpMethod.GET, uri); - return this.restTemplate.exchange(request, String.class); + private EntityExchangeResult<String> performRequest(URI uri, @Nullable String cookie) { + return browserClient().get() + .uri(uri) + .accept(MediaType.TEXT_HTML) + .headers((headers) -> headers.addAll(getHeaders(cookie))) + .exchangeSuccessfully() + .expectBody(String.class) + .returnResult(); } private HttpHeaders getHeaders(@Nullable String cookie) { @@ -131,13 +139,15 @@ class SampleSessionJdbcApplicationTests { return "Basic " + Base64.getEncoder().encodeToString("user:password".getBytes()); } - private ResponseEntity<Map<String, Object>> getSessions() { - HttpHeaders headers = getHeaders(null); - RequestEntity<Object> request = new RequestEntity<>(headers, HttpMethod.GET, - URI.create("/actuator/sessions?username=user")); + private EntityExchangeResult<Map<String, Object>> getSessions() { ParameterizedTypeReference<Map<String, Object>> stringObjectMap = new ParameterizedTypeReference<>() { }; - return this.restTemplate.exchange(request, stringObjectMap); + return this.restTestClient.get() + .uri("/actuator/sessions?username=user") + .headers((headers) -> headers.addAll(getHeaders(null))) + .exchangeSuccessfully() + .expectBody(stringObjectMap) + .returnResult(); } } diff --git a/smoke-test/spring-boot-smoke-test-test/src/test/java/smoketest/test/SampleTestApplicationWebIntegrationTests.java b/smoke-test/spring-boot-smoke-test-test/src/test/java/smoketest/test/SampleTestApplicationWebIntegrationTests.java index bbe455b73e7..dcfe270afc1 100644 --- a/smoke-test/spring-boot-smoke-test-test/src/test/java/smoketest/test/SampleTestApplicationWebIntegrationTests.java +++ b/smoke-test/spring-boot-smoke-test-test/src/test/java/smoketest/test/SampleTestApplicationWebIntegrationTests.java @@ -24,14 +24,12 @@ import smoketest.test.service.VehicleDetailsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.jdbc.test.autoconfigure.AutoConfigureTestDatabase; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.http.HttpStatus; import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.client.RestTestClient; -import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; /** @@ -42,13 +40,13 @@ import static org.mockito.BDDMockito.given; */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @AutoConfigureTestDatabase -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleTestApplicationWebIntegrationTests { private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber("01234567890123456"); @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @MockitoBean private VehicleDetailsService vehicleDetailsService; @@ -60,8 +58,7 @@ class SampleTestApplicationWebIntegrationTests { @Test void test() { - assertThat(this.restTemplate.getForEntity("/{username}/vehicle", String.class, "sframework").getStatusCode()) - .isEqualTo(HttpStatus.OK); + this.restTestClient.get().uri("/{username}/vehicle", "sframework").exchange().expectStatus().isOk(); } } diff --git a/smoke-test/spring-boot-smoke-test-testng/src/test/java/smoketest/testng/SampleTestNGApplicationTests.java b/smoke-test/spring-boot-smoke-test-testng/src/test/java/smoketest/testng/SampleTestNGApplicationTests.java index 43dd3da3bc5..6468ca6a821 100644 --- a/smoke-test/spring-boot-smoke-test-testng/src/test/java/smoketest/testng/SampleTestNGApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-testng/src/test/java/smoketest/testng/SampleTestNGApplicationTests.java @@ -19,15 +19,11 @@ package smoketest.testng; import org.testng.annotations.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; - -import static org.assertj.core.api.Assertions.assertThat; +import org.springframework.test.web.servlet.client.RestTestClient; /** * Basic integration tests for demo application. @@ -35,17 +31,15 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient public class SampleTestNGApplicationTests extends AbstractTestNGSpringContextTests { @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @Test public void testHome() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).isEqualTo("Hello World"); + this.restTestClient.get().uri("/").exchangeSuccessfully().expectBody(String.class).isEqualTo("Hello World"); } } diff --git a/smoke-test/spring-boot-smoke-test-tomcat-jsp/src/test/java/smoketest/tomcat/jsp/SampleWebJspApplicationTests.java b/smoke-test/spring-boot-smoke-test-tomcat-jsp/src/test/java/smoketest/tomcat/jsp/SampleWebJspApplicationTests.java index d26086799d0..68b442685f7 100644 --- a/smoke-test/spring-boot-smoke-test-tomcat-jsp/src/test/java/smoketest/tomcat/jsp/SampleWebJspApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-tomcat-jsp/src/test/java/smoketest/tomcat/jsp/SampleWebJspApplicationTests.java @@ -19,12 +19,10 @@ package smoketest.tomcat.jsp; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -34,17 +32,19 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleWebJspApplicationTests { @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @Test void testJspWithEl() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("/resources/text.txt"); + this.restTestClient.get() + .uri("/") + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("/resources/text.txt")); } } diff --git a/smoke-test/spring-boot-smoke-test-tomcat-multi-connectors/build.gradle b/smoke-test/spring-boot-smoke-test-tomcat-multi-connectors/build.gradle index 04b2df6f4de..5df0de47827 100644 --- a/smoke-test/spring-boot-smoke-test-tomcat-multi-connectors/build.gradle +++ b/smoke-test/spring-boot-smoke-test-tomcat-multi-connectors/build.gradle @@ -24,7 +24,7 @@ dependencies { implementation(project(":starter:spring-boot-starter-webmvc")) testImplementation(project(":starter:spring-boot-starter-webmvc-test")) - testImplementation(project(":module:spring-boot-restclient")) + testImplementation(project(":module:spring-boot-resttestclient")) testImplementation("org.apache.httpcomponents.client5:httpclient5") } diff --git a/smoke-test/spring-boot-smoke-test-tomcat-multi-connectors/src/test/java/smoketest/tomcat/multiconnector/SampleTomcatTwoConnectorsApplicationTests.java b/smoke-test/spring-boot-smoke-test-tomcat-multi-connectors/src/test/java/smoketest/tomcat/multiconnector/SampleTomcatTwoConnectorsApplicationTests.java index 9f2f9bba732..c76ea1fd632 100644 --- a/smoke-test/spring-boot-smoke-test-tomcat-multi-connectors/src/test/java/smoketest/tomcat/multiconnector/SampleTomcatTwoConnectorsApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-tomcat-multi-connectors/src/test/java/smoketest/tomcat/multiconnector/SampleTomcatTwoConnectorsApplicationTests.java @@ -22,8 +22,7 @@ import org.junit.jupiter.api.Test; import smoketest.tomcat.multiconnector.SampleTomcatTwoConnectorsApplicationTests.Ports; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.TrustAllTlsRequestFactory; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.context.TestConfiguration; @@ -34,8 +33,7 @@ import org.springframework.boot.web.server.Ssl; import org.springframework.boot.web.server.context.WebServerInitializedEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Import; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -47,7 +45,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @Import(Ports.class) -@AutoConfigureTestRestTemplate class SampleTomcatTwoConnectorsApplicationTests { @LocalServerPort @@ -56,9 +53,6 @@ class SampleTomcatTwoConnectorsApplicationTests { @Autowired private Ports ports; - @Autowired - private TestRestTemplate restTemplate; - @Autowired private AbstractConfigurableWebServerFactory webServerFactory; @@ -73,14 +67,14 @@ class SampleTomcatTwoConnectorsApplicationTests { void testHello() { assertThat(this.ports.getHttpsPort()).isEqualTo(this.port); assertThat(this.ports.getHttpPort()).isNotEqualTo(this.port); - ResponseEntity<String> entity = this.restTemplate - .getForEntity("http://localhost:" + this.ports.getHttpPort() + "/hello", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).isEqualTo("hello"); - ResponseEntity<String> httpsEntity = this.restTemplate.getForEntity("https://localhost:" + this.port + "/hello", - String.class); - assertThat(httpsEntity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(httpsEntity.getBody()).isEqualTo("hello"); + RestTestClient httpClient = RestTestClient.bindToServer() + .baseUrl("http://localhost:" + this.ports.getHttpPort()) + .build(); + httpClient.get().uri("/hello").exchangeSuccessfully().expectBody(String.class).isEqualTo("hello"); + RestTestClient httpsClient = RestTestClient.bindToServer(TrustAllTlsRequestFactory.create()) + .baseUrl("https://localhost:" + this.port) + .build(); + httpsClient.get().uri("/hello").exchangeSuccessfully().expectBody(String.class).isEqualTo("hello"); } @TestConfiguration diff --git a/smoke-test/spring-boot-smoke-test-tomcat-ssl/build.gradle b/smoke-test/spring-boot-smoke-test-tomcat-ssl/build.gradle index fd86d66635a..b08fc2ff4a4 100644 --- a/smoke-test/spring-boot-smoke-test-tomcat-ssl/build.gradle +++ b/smoke-test/spring-boot-smoke-test-tomcat-ssl/build.gradle @@ -25,7 +25,7 @@ dependencies { implementation(project(":starter:spring-boot-starter-webmvc")) testImplementation(project(":starter:spring-boot-starter-webmvc-test")) - testImplementation(project(":module:spring-boot-restclient")) + testImplementation(project(":module:spring-boot-resttestclient")) testImplementation("org.apache.httpcomponents.client5:httpclient5") } diff --git a/smoke-test/spring-boot-smoke-test-tomcat-ssl/src/test/java/smoketest/tomcat/ssl/SampleTomcatSslApplicationTests.java b/smoke-test/spring-boot-smoke-test-tomcat-ssl/src/test/java/smoketest/tomcat/ssl/SampleTomcatSslApplicationTests.java index 1f451ef9c14..8f5d57dd901 100644 --- a/smoke-test/spring-boot-smoke-test-tomcat-ssl/src/test/java/smoketest/tomcat/ssl/SampleTomcatSslApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-tomcat-ssl/src/test/java/smoketest/tomcat/ssl/SampleTomcatSslApplicationTests.java @@ -19,24 +19,24 @@ package smoketest.tomcat.ssl; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.TrustAllTlsRequestFactory; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.boot.web.server.AbstractConfigurableWebServerFactory; import org.springframework.boot.web.server.Ssl; import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; import org.springframework.test.json.JsonContent; +import org.springframework.test.web.servlet.client.EntityExchangeResult; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -@AutoConfigureTestRestTemplate class SampleTomcatSslApplicationTests { - @Autowired - private TestRestTemplate restTemplate; + @LocalServerPort + private int port; @Autowired private AbstractConfigurableWebServerFactory webServerFactory; @@ -50,16 +50,17 @@ class SampleTomcatSslApplicationTests { @Test void testHome() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).isEqualTo("Hello, world"); + restTestClient().get().uri("/").exchangeSuccessfully().expectBody(String.class).isEqualTo("Hello, world"); } @Test void testSslInfo() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/actuator/info", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - String body = entity.getBody(); + EntityExchangeResult<String> result = restTestClient().get() + .uri("/actuator/info") + .exchange() + .returnResult(String.class); + assertThat(result.getStatus()).isEqualTo(HttpStatus.OK); + String body = result.getResponseBody(); assertThat(body).isNotNull(); JsonContent json = new JsonContent(body); assertThat(json).extractingPath("ssl.bundles[0].name").isEqualTo("ssldemo"); @@ -78,9 +79,12 @@ class SampleTomcatSslApplicationTests { @Test void testSslHealth() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/actuator/health", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); - String body = entity.getBody(); + EntityExchangeResult<String> result = restTestClient().get() + .uri("/actuator/health") + .exchange() + .returnResult(String.class); + assertThat(result.getStatus()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); + String body = result.getResponseBody(); assertThat(body).isNotNull(); JsonContent json = new JsonContent(body); assertThat(json).extractingPath("status").isEqualTo("OUT_OF_SERVICE"); @@ -98,4 +102,10 @@ class SampleTomcatSslApplicationTests { .startsWith("Not valid after "); } + private RestTestClient restTestClient() { + return RestTestClient.bindToServer(TrustAllTlsRequestFactory.create()) + .baseUrl("https://localhost:" + this.port) + .build(); + } + } diff --git a/smoke-test/spring-boot-smoke-test-tomcat/src/test/java/smoketest/tomcat/NonAutoConfigurationSampleTomcatApplicationTests.java b/smoke-test/spring-boot-smoke-test-tomcat/src/test/java/smoketest/tomcat/NonAutoConfigurationSampleTomcatApplicationTests.java index f7a91ea3b72..9631cf054d6 100644 --- a/smoke-test/spring-boot-smoke-test-tomcat/src/test/java/smoketest/tomcat/NonAutoConfigurationSampleTomcatApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-tomcat/src/test/java/smoketest/tomcat/NonAutoConfigurationSampleTomcatApplicationTests.java @@ -24,8 +24,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.http.converter.autoconfigure.HttpMessageConvertersAutoConfiguration; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.tomcat.autoconfigure.servlet.TomcatServletWebServerAutoConfiguration; @@ -34,10 +33,7 @@ import org.springframework.boot.webmvc.autoconfigure.WebMvcAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; - -import static org.assertj.core.api.Assertions.assertThat; +import org.springframework.test.web.servlet.client.RestTestClient; /** * Basic integration tests for demo application. @@ -45,17 +41,15 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class NonAutoConfigurationSampleTomcatApplicationTests { @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @Test void testHome() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).isEqualTo("Hello World"); + this.restTestClient.get().uri("/").exchangeSuccessfully().expectBody(String.class).isEqualTo("Hello World"); } @Configuration(proxyBeanMethods = false) diff --git a/smoke-test/spring-boot-smoke-test-tomcat/src/test/java/smoketest/tomcat/SampleTomcatApplicationTests.java b/smoke-test/spring-boot-smoke-test-tomcat/src/test/java/smoketest/tomcat/SampleTomcatApplicationTests.java index 303bc1269a6..3111904e24d 100644 --- a/smoke-test/spring-boot-smoke-test-tomcat/src/test/java/smoketest/tomcat/SampleTomcatApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-tomcat/src/test/java/smoketest/tomcat/SampleTomcatApplicationTests.java @@ -29,24 +29,20 @@ import smoketest.tomcat.util.RandomStringUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.http.client.ClientHttpRequestFactoryBuilder; -import org.springframework.boot.restclient.RestTemplateBuilder; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.system.CapturedOutput; import org.springframework.boot.test.system.OutputCaptureExtension; +import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.boot.tomcat.TomcatWebServer; import org.springframework.boot.web.server.servlet.context.ServletWebServerApplicationContext; import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.http.client.JdkClientHttpRequestFactory; +import org.springframework.test.web.servlet.client.EntityExchangeResult; +import org.springframework.test.web.servlet.client.RestTestClient; import org.springframework.util.StreamUtils; import static org.assertj.core.api.Assertions.assertThat; @@ -61,12 +57,14 @@ import static org.assertj.core.api.Assertions.assertThat; */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @ExtendWith(OutputCaptureExtension.class) -@AutoConfigureTestRestTemplate -@SuppressWarnings("removal") +@AutoConfigureRestTestClient class SampleTomcatApplicationTests { + @LocalServerPort + private int port; + @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @Autowired private ApplicationContext applicationContext; @@ -76,21 +74,29 @@ class SampleTomcatApplicationTests { @Test void testHome() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getHeaders().get(HttpHeaders.CONTENT_ENCODING)).isNull(); - assertThat(entity.getBody()).isEqualTo("Hello World"); + EntityExchangeResult<String> result = this.restTestClient.get().uri("/").exchange().returnResult(String.class); + assertThat(result.getStatus()).isEqualTo(HttpStatus.OK); + assertThat(result.getResponseHeaders().get(HttpHeaders.CONTENT_ENCODING)).isNull(); + assertThat(result.getResponseBody()).isEqualTo("Hello World"); } @Test void testCompression() throws IOException { - HttpHeaders requestHeaders = new HttpHeaders(); - requestHeaders.set("Accept-Encoding", "gzip"); - HttpEntity<?> requestEntity = new HttpEntity<>(requestHeaders); - ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET, requestEntity, byte[].class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getHeaders().get(HttpHeaders.CONTENT_ENCODING)).containsExactly("gzip"); - try (GZIPInputStream inflater = new GZIPInputStream(new ByteArrayInputStream(entity.getBody()))) { + // Use a client with automatic decompression disabled so that the raw gzipped + // response body and the Content-Encoding header can be verified. + JdkClientHttpRequestFactory requestFactory = new JdkClientHttpRequestFactory(); + requestFactory.enableCompression(false); + RestTestClient nonDecompressingClient = RestTestClient.bindToServer(requestFactory) + .baseUrl("http://localhost:" + this.port) + .build(); + EntityExchangeResult<byte[]> result = nonDecompressingClient.get() + .uri("/") + .headers((headers) -> headers.set("Accept-Encoding", "gzip")) + .exchange() + .returnResult(byte[].class); + assertThat(result.getStatus()).isEqualTo(HttpStatus.OK); + assertThat(result.getResponseHeaders().get(HttpHeaders.CONTENT_ENCODING)).containsExactly("gzip"); + try (GZIPInputStream inflater = new GZIPInputStream(new ByteArrayInputStream(result.getResponseBody()))) { assertThat(StreamUtils.copyToString(inflater, StandardCharsets.UTF_8)).isEqualTo("Hello World"); } } @@ -107,8 +113,11 @@ class SampleTomcatApplicationTests { @Test void testMaxHttpResponseHeaderSize(CapturedOutput output) { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/max-http-response-header", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); + this.restTestClient.get() + .uri("/max-http-response-header") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); assertThat(output).contains( "threw exception [Request processing failed: org.apache.coyote.http11.HeadersTooLargeException: An attempt was made to write more data to the response headers than there was room available in the buffer. Increase maxHttpHeaderSize on the connector or write less data into the response headers.]"); } @@ -116,23 +125,13 @@ class SampleTomcatApplicationTests { @Test void testMaxHttpRequestHeaderSize(CapturedOutput output) { String headerValue = RandomStringUtil.getRandomBase64EncodedString(this.maxHttpRequestHeaderSize + 1); - HttpHeaders headers = new HttpHeaders(); - headers.add("x-max-request-header", headerValue); - HttpEntity<?> httpEntity = new HttpEntity<>(headers); - ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, httpEntity, String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); + this.restTestClient.get() + .uri("/") + .headers((headers) -> headers.add("x-max-request-header", headerValue)) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.BAD_REQUEST); assertThat(output).contains("java.lang.IllegalArgumentException: Request header is too large"); } - @TestConfiguration - static class DisableCompressionConfiguration { - - @Bean - RestTemplateBuilder restTemplateBuilder() { - return new RestTemplateBuilder().requestFactoryBuilder(ClientHttpRequestFactoryBuilder.jdk() - .withCustomizer((factory) -> factory.enableCompression(false))); - } - - } - } diff --git a/smoke-test/spring-boot-smoke-test-traditional/src/test/java/smoketest/traditional/SampleTraditionalApplicationTests.java b/smoke-test/spring-boot-smoke-test-traditional/src/test/java/smoketest/traditional/SampleTraditionalApplicationTests.java index 43258806303..9fd75e9456f 100644 --- a/smoke-test/spring-boot-smoke-test-traditional/src/test/java/smoketest/traditional/SampleTraditionalApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-traditional/src/test/java/smoketest/traditional/SampleTraditionalApplicationTests.java @@ -19,12 +19,10 @@ package smoketest.traditional; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -34,26 +32,28 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleTraditionalApplicationTests { @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @Test void testHomeJsp() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - String body = entity.getBody(); - assertThat(body).contains("<html>").contains("<h1>Home</h1>"); + this.restTestClient.get() + .uri("/") + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("<html>").contains("<h1>Home</h1>")); } @Test void testStaticPage() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/index.html", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - String body = entity.getBody(); - assertThat(body).contains("<html>").contains("<h1>Hello</h1>"); + this.restTestClient.get() + .uri("/index.html") + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("<html>").contains("<h1>Hello</h1>")); } } diff --git a/smoke-test/spring-boot-smoke-test-web-freemarker/src/test/java/smoketest/freemarker/SampleWebFreeMarkerApplicationTests.java b/smoke-test/spring-boot-smoke-test-web-freemarker/src/test/java/smoketest/freemarker/SampleWebFreeMarkerApplicationTests.java index 5a54887a79a..4c792c09fa2 100644 --- a/smoke-test/spring-boot-smoke-test-web-freemarker/src/test/java/smoketest/freemarker/SampleWebFreeMarkerApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-web-freemarker/src/test/java/smoketest/freemarker/SampleWebFreeMarkerApplicationTests.java @@ -16,21 +16,15 @@ package smoketest.freemarker; -import java.util.Arrays; - import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -41,43 +35,43 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleWebFreeMarkerApplicationTests { @Autowired - private TestRestTemplate testRestTemplate; + private RestTestClient restTestClient; @Test void testFreeMarkerTemplate() { - ResponseEntity<String> entity = this.testRestTemplate.getForEntity("/", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("Hello, Andy"); + this.restTestClient.get() + .uri("/") + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("Hello, Andy")); } @Test void testFreeMarkerErrorTemplate() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - HttpEntity<String> requestEntity = new HttpEntity<>(headers); - - ResponseEntity<String> responseEntity = this.testRestTemplate.exchange("/does-not-exist", HttpMethod.GET, - requestEntity, String.class); - - assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); - assertThat(responseEntity.getBody()).contains("Something went wrong: 404 Not Found"); + this.restTestClient.get() + .uri("/does-not-exist") + .accept(MediaType.TEXT_HTML) + .exchange() + .expectStatus() + .isNotFound() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("Something went wrong: 404 Not Found")); } @Test void templateErrorPageForSpecificStatusCode() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - HttpEntity<String> requestEntity = new HttpEntity<>(headers); - - ResponseEntity<String> responseEntity = this.testRestTemplate.exchange("/insufficient-storage", HttpMethod.GET, - requestEntity, String.class); - - assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.INSUFFICIENT_STORAGE); - assertThat(responseEntity.getBody()).contains("We are out of storage"); + this.restTestClient.get() + .uri("/insufficient-storage") + .accept(MediaType.TEXT_HTML) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INSUFFICIENT_STORAGE) + .expectBody(String.class) + .value((body) -> assertThat(body).contains("We are out of storage")); } } diff --git a/smoke-test/spring-boot-smoke-test-web-groovy-templates/src/test/java/smoketest/groovytemplates/SampleGroovyTemplateApplicationTests.java b/smoke-test/spring-boot-smoke-test-web-groovy-templates/src/test/java/smoketest/groovytemplates/SampleGroovyTemplateApplicationTests.java index 8e96b6a433a..141b4983855 100644 --- a/smoke-test/spring-boot-smoke-test-web-groovy-templates/src/test/java/smoketest/groovytemplates/SampleGroovyTemplateApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-web-groovy-templates/src/test/java/smoketest/groovytemplates/SampleGroovyTemplateApplicationTests.java @@ -16,18 +16,14 @@ package smoketest.groovytemplates; -import java.net.URI; - import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; @@ -39,21 +35,21 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.http.clients.redirects=dont-follow") -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleGroovyTemplateApplicationTests { @LocalServerPort private int port; @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @Test void testHome() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("<title>Messages"); - assertThat(entity.getBody()).doesNotContain("layout:fragment"); + this.restTestClient.get().uri("/").exchangeSuccessfully().expectBody(String.class).value((body) -> { + assertThat(body).contains("<title>Messages"); + assertThat(body).doesNotContain("layout:fragment"); + }); } @Test @@ -61,16 +57,21 @@ class SampleGroovyTemplateApplicationTests { MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); map.set("text", "FOO text"); map.set("summary", "FOO"); - URI location = this.restTemplate.postForLocation("/", map); - assertThat(location).isNotNull(); - assertThat(location.toString()).contains("localhost:" + this.port); + this.restTestClient.post() + .uri("/") + .body(map) + .exchange() + .expectHeader() + .value("Location", (location) -> assertThat(location).contains("localhost:" + this.port)); } @Test void testCss() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/css/bootstrap.min.css", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("body"); + this.restTestClient.get() + .uri("/css/bootstrap.min.css") + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("body")); } } diff --git a/smoke-test/spring-boot-smoke-test-web-jsp/src/test/java/smoketest/jsp/SampleWebJspApplicationTests.java b/smoke-test/spring-boot-smoke-test-web-jsp/src/test/java/smoketest/jsp/SampleWebJspApplicationTests.java index 00df3c960a7..57c2f81d34e 100644 --- a/smoke-test/spring-boot-smoke-test-web-jsp/src/test/java/smoketest/jsp/SampleWebJspApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-web-jsp/src/test/java/smoketest/jsp/SampleWebJspApplicationTests.java @@ -16,22 +16,15 @@ package smoketest.jsp; -import java.net.URI; -import java.util.Arrays; - import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.RequestEntity; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -41,27 +34,31 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleWebJspApplicationTests { @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @Test void testJspWithEl() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("/resources/text.txt"); + this.restTestClient.get() + .uri("/") + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("/resources/text.txt")); } @Test void customErrorPage() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - RequestEntity<Void> request = new RequestEntity<>(headers, HttpMethod.GET, URI.create("/foo")); - ResponseEntity<String> entity = this.restTemplate.exchange(request, String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); - assertThat(entity.getBody()).contains("Something went wrong: 500 Internal Server Error"); + this.restTestClient.get() + .uri("/foo") + .accept(MediaType.TEXT_HTML) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectBody(String.class) + .value((body) -> assertThat(body).contains("Something went wrong: 500 Internal Server Error")); } } diff --git a/smoke-test/spring-boot-smoke-test-web-method-security/src/test/java/smoketest/security/method/SampleMethodSecurityApplicationTests.java b/smoke-test/spring-boot-smoke-test-web-method-security/src/test/java/smoketest/security/method/SampleMethodSecurityApplicationTests.java index 8c969ad4cec..552182ae9b0 100644 --- a/smoke-test/spring-boot-smoke-test-web-method-security/src/test/java/smoketest/security/method/SampleMethodSecurityApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-web-method-security/src/test/java/smoketest/security/method/SampleMethodSecurityApplicationTests.java @@ -22,18 +22,17 @@ import java.util.Collections; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.http.client.ClientHttpRequestFactoryBuilder; +import org.springframework.boot.http.client.HttpClientSettings; +import org.springframework.boot.http.client.HttpRedirects; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.http.client.support.BasicAuthenticationInterceptor; +import org.springframework.test.web.servlet.client.EntityExchangeResult; +import org.springframework.test.web.servlet.client.RestTestClient; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; @@ -47,79 +46,96 @@ import static org.assertj.core.api.Assertions.assertThat; */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.http.clients.imperative.factory=simple") -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleMethodSecurityApplicationTests { @LocalServerPort private int port; @Autowired - private TestRestTemplate restTemplate; + private RestTestClient rest; + + private RestTestClient followingRedirects() { + return RestTestClient + .bindToServer(ClientHttpRequestFactoryBuilder.detect() + .build(HttpClientSettings.defaults().withRedirects(HttpRedirects.FOLLOW_WHEN_POSSIBLE))) + .baseUrl("http://localhost:" + this.port) + .build(); + } + + private RestTestClient nonFollowingRedirects() { + return RestTestClient + .bindToServer(ClientHttpRequestFactoryBuilder.detect() + .build(HttpClientSettings.defaults().withRedirects(HttpRedirects.DONT_FOLLOW))) + .baseUrl("http://localhost:" + this.port) + .build(); + } @Test void testHome() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Collections.singletonList(MediaType.TEXT_HTML)); - ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, new HttpEntity<>(headers), - String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + followingRedirects().get().uri("/").accept(MediaType.TEXT_HTML).exchange().expectStatus().isOk(); } @Test void testLogin() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Collections.singletonList(MediaType.TEXT_HTML)); MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.set("username", "admin"); form.set("password", "admin"); - ResponseEntity<String> entity = this.restTemplate.exchange("/login", HttpMethod.POST, - new HttpEntity<>(form, headers), String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - URI location = entity.getHeaders().getLocation(); + EntityExchangeResult<String> result = nonFollowingRedirects().post() + .uri("/login") + .contentType(MediaType.APPLICATION_FORM_URLENCODED) + .accept(MediaType.TEXT_HTML) + .body(form) + .exchange() + .returnResult(String.class); + assertThat(result.getStatus()).isEqualTo(HttpStatus.FOUND); + URI location = result.getResponseHeaders().getLocation(); assertThat(location).isNotNull(); assertThat(location.toString()).endsWith(this.port + "/"); } @Test void testDenied() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Collections.singletonList(MediaType.TEXT_HTML)); MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.set("username", "user"); form.set("password", "user"); - ResponseEntity<String> entity = this.restTemplate.exchange("/login", HttpMethod.POST, - new HttpEntity<>(form, headers), String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - String cookie = entity.getHeaders().getFirst("Set-Cookie"); - headers.set("Cookie", cookie); - URI location = entity.getHeaders().getLocation(); + EntityExchangeResult<String> result = nonFollowingRedirects().post() + .uri("/login") + .contentType(MediaType.APPLICATION_FORM_URLENCODED) + .accept(MediaType.TEXT_HTML) + .body(form) + .exchange() + .returnResult(String.class); + assertThat(result.getStatus()).isEqualTo(HttpStatus.FOUND); + String cookie = result.getResponseHeaders().getFirst("Set-Cookie"); + URI location = result.getResponseHeaders().getLocation(); assertThat(location).isNotNull(); - ResponseEntity<String> page = this.restTemplate.exchange(location, HttpMethod.GET, new HttpEntity<>(headers), - String.class); - assertThat(page.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); - assertThat(page.getBody()).contains("Access denied"); + EntityExchangeResult<String> page = this.rest.get().uri(location).headers((headers) -> { + headers.setAccept(Collections.singletonList(MediaType.TEXT_HTML)); + headers.set("Cookie", cookie); + }).exchange().returnResult(String.class); + assertThat(page.getStatus()).isEqualTo(HttpStatus.FORBIDDEN); + assertThat(page.getResponseBody()).contains("Access denied"); } @Test void testManagementProtected() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); - ResponseEntity<String> entity = this.restTemplate.exchange("/actuator/beans", HttpMethod.GET, - new HttpEntity<>(headers), String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + this.rest.get() + .uri("/actuator/beans") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isUnauthorized(); } @Test void testManagementAuthorizedAccess() { - BasicAuthenticationInterceptor basicAuthInterceptor = new BasicAuthenticationInterceptor("admin", "admin"); - this.restTemplate.getRestTemplate().getInterceptors().add(basicAuthInterceptor); - try { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/actuator/beans", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - } - finally { - this.restTemplate.getRestTemplate().getInterceptors().remove(basicAuthInterceptor); - } + this.rest.get() + .uri("/actuator/beans") + .headers((headers) -> headers.setBasicAuth("admin", "admin")) + .exchange() + .expectStatus() + .isOk(); } } diff --git a/smoke-test/spring-boot-smoke-test-web-mustache/src/test/java/smoketest/mustache/SampleWebMustacheApplicationTests.java b/smoke-test/spring-boot-smoke-test-web-mustache/src/test/java/smoketest/mustache/SampleWebMustacheApplicationTests.java index 68cba59163b..4ca963db0f9 100644 --- a/smoke-test/spring-boot-smoke-test-web-mustache/src/test/java/smoketest/mustache/SampleWebMustacheApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-web-mustache/src/test/java/smoketest/mustache/SampleWebMustacheApplicationTests.java @@ -16,21 +16,15 @@ package smoketest.mustache; -import java.util.Arrays; - import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -41,61 +35,67 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleWebMustacheApplicationTests { @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @Test void testMustacheTemplate() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("Hello, Andy"); + this.restTestClient.get() + .uri("/") + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("Hello, Andy")); } @Test void testMustacheErrorTemplate() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - HttpEntity<String> requestEntity = new HttpEntity<>(headers); - ResponseEntity<String> responseEntity = this.restTemplate.exchange("/does-not-exist", HttpMethod.GET, - requestEntity, String.class); - assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); - assertThat(responseEntity.getBody()).contains("Something went wrong: 404 Not Found"); + this.restTestClient.get() + .uri("/does-not-exist") + .accept(MediaType.TEXT_HTML) + .exchange() + .expectStatus() + .isNotFound() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("Something went wrong: 404 Not Found")); } @Test void test503HtmlResource() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - HttpEntity<String> requestEntity = new HttpEntity<>(headers); - ResponseEntity<String> entity = this.restTemplate.exchange("/serviceUnavailable", HttpMethod.GET, requestEntity, - String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); - assertThat(entity.getBody()).contains("I'm a 503"); + this.restTestClient.get() + .uri("/serviceUnavailable") + .accept(MediaType.TEXT_HTML) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE) + .expectBody(String.class) + .value((body) -> assertThat(body).contains("I'm a 503")); } @Test void test5xxHtmlResource() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - HttpEntity<String> requestEntity = new HttpEntity<>(headers); - ResponseEntity<String> entity = this.restTemplate.exchange("/bang", HttpMethod.GET, requestEntity, - String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); - assertThat(entity.getBody()).contains("I'm a 5xx"); + this.restTestClient.get() + .uri("/bang") + .accept(MediaType.TEXT_HTML) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectBody(String.class) + .value((body) -> assertThat(body).contains("I'm a 5xx")); } @Test void test507Template() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - HttpEntity<String> requestEntity = new HttpEntity<>(headers); - ResponseEntity<String> entity = this.restTemplate.exchange("/insufficientStorage", HttpMethod.GET, - requestEntity, String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INSUFFICIENT_STORAGE); - assertThat(entity.getBody()).contains("I'm a 507"); + this.restTestClient.get() + .uri("/insufficientStorage") + .accept(MediaType.TEXT_HTML) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INSUFFICIENT_STORAGE) + .expectBody(String.class) + .value((body) -> assertThat(body).contains("I'm a 507")); } } diff --git a/smoke-test/spring-boot-smoke-test-web-secure-custom/src/test/java/smoketest/web/secure/custom/SampleWebSecureCustomApplicationTests.java b/smoke-test/spring-boot-smoke-test-web-secure-custom/src/test/java/smoketest/web/secure/custom/SampleWebSecureCustomApplicationTests.java index 77f7469b70a..b16c34ab450 100644 --- a/smoke-test/spring-boot-smoke-test-web-secure-custom/src/test/java/smoketest/web/secure/custom/SampleWebSecureCustomApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-web-secure-custom/src/test/java/smoketest/web/secure/custom/SampleWebSecureCustomApplicationTests.java @@ -17,23 +17,21 @@ package smoketest.web.secure.custom; import java.net.URI; -import java.util.Collections; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.http.client.ClientHttpRequestFactoryBuilder; +import org.springframework.boot.http.client.HttpClientSettings; import org.springframework.boot.http.client.HttpRedirects; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.EntityExchangeResult; +import org.springframework.test.web.servlet.client.RestTestClient; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; @@ -46,49 +44,60 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Scott Frederick */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleWebSecureCustomApplicationTests { @Autowired - private TestRestTemplate restTemplate; + private RestTestClient rest; @LocalServerPort private int port; + private RestTestClient nonFollowingRedirect() { + return RestTestClient + .bindToServer(ClientHttpRequestFactoryBuilder.detect() + .build(HttpClientSettings.defaults().withRedirects(HttpRedirects.DONT_FOLLOW))) + .baseUrl("http://localhost:" + this.port) + .build(); + } + @Test void testHome() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Collections.singletonList(MediaType.TEXT_HTML)); - ResponseEntity<String> entity = this.restTemplate.withRedirects(HttpRedirects.DONT_FOLLOW) - .exchange("/", HttpMethod.GET, new HttpEntity<>(headers), String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - URI location = entity.getHeaders().getLocation(); + EntityExchangeResult<String> result = nonFollowingRedirect().get() + .uri("/") + .accept(MediaType.TEXT_HTML) + .exchange() + .returnResult(String.class); + assertThat(result.getStatus()).isEqualTo(HttpStatus.FOUND); + URI location = result.getResponseHeaders().getLocation(); assertThat(location).isNotNull(); assertThat(location.toString()).endsWith(this.port + "/login"); } @Test void testLoginPage() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Collections.singletonList(MediaType.TEXT_HTML)); - ResponseEntity<String> entity = this.restTemplate.exchange("/login", HttpMethod.GET, new HttpEntity<>(headers), - String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("<title>Login"); + this.rest.get() + .uri("/login") + .accept(MediaType.TEXT_HTML) + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("Login")); } @Test void testLogin() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Collections.singletonList(MediaType.TEXT_HTML)); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap form = new LinkedMultiValueMap<>(); form.set("username", "user"); form.set("password", "password"); - ResponseEntity entity = this.restTemplate.withRedirects(HttpRedirects.DONT_FOLLOW) - .exchange("/login", HttpMethod.POST, new HttpEntity<>(form, headers), String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - URI location = entity.getHeaders().getLocation(); + EntityExchangeResult result = nonFollowingRedirect().post() + .uri("/login") + .contentType(MediaType.APPLICATION_FORM_URLENCODED) + .accept(MediaType.TEXT_HTML) + .body(form) + .exchange() + .returnResult(String.class); + assertThat(result.getStatus()).isEqualTo(HttpStatus.FOUND); + URI location = result.getResponseHeaders().getLocation(); assertThat(location).isNotNull(); assertThat(location.toString()).endsWith(this.port + "/"); } diff --git a/smoke-test/spring-boot-smoke-test-web-secure-jdbc/src/test/java/smoketest/web/secure/jdbc/SampleWebSecureJdbcApplicationTests.java b/smoke-test/spring-boot-smoke-test-web-secure-jdbc/src/test/java/smoketest/web/secure/jdbc/SampleWebSecureJdbcApplicationTests.java index 8b46bff3e25..82ba02cf198 100644 --- a/smoke-test/spring-boot-smoke-test-web-secure-jdbc/src/test/java/smoketest/web/secure/jdbc/SampleWebSecureJdbcApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-web-secure-jdbc/src/test/java/smoketest/web/secure/jdbc/SampleWebSecureJdbcApplicationTests.java @@ -17,23 +17,21 @@ package smoketest.web.secure.jdbc; import java.net.URI; -import java.util.Collections; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.http.client.ClientHttpRequestFactoryBuilder; +import org.springframework.boot.http.client.HttpClientSettings; import org.springframework.boot.http.client.HttpRedirects; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.EntityExchangeResult; +import org.springframework.test.web.servlet.client.RestTestClient; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; @@ -46,49 +44,60 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Scott Frederick */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleWebSecureJdbcApplicationTests { @Autowired - private TestRestTemplate restTemplate; + private RestTestClient rest; @LocalServerPort private int port; + private RestTestClient nonFollowingRedirect() { + return RestTestClient + .bindToServer(ClientHttpRequestFactoryBuilder.detect() + .build(HttpClientSettings.defaults().withRedirects(HttpRedirects.DONT_FOLLOW))) + .baseUrl("http://localhost:" + this.port) + .build(); + } + @Test void testHome() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Collections.singletonList(MediaType.TEXT_HTML)); - ResponseEntity entity = this.restTemplate.withRedirects(HttpRedirects.DONT_FOLLOW) - .exchange("/", HttpMethod.GET, new HttpEntity<>(headers), String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - URI location = entity.getHeaders().getLocation(); + EntityExchangeResult result = nonFollowingRedirect().get() + .uri("/") + .accept(MediaType.TEXT_HTML) + .exchange() + .returnResult(String.class); + assertThat(result.getStatus()).isEqualTo(HttpStatus.FOUND); + URI location = result.getResponseHeaders().getLocation(); assertThat(location).isNotNull(); assertThat(location.toString()).endsWith(this.port + "/login"); } @Test void testLoginPage() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Collections.singletonList(MediaType.TEXT_HTML)); - ResponseEntity entity = this.restTemplate.exchange("/login", HttpMethod.GET, new HttpEntity<>(headers), - String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("Login"); + this.rest.get() + .uri("/login") + .accept(MediaType.TEXT_HTML) + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("Login")); } @Test void testLogin() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Collections.singletonList(MediaType.TEXT_HTML)); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap form = new LinkedMultiValueMap<>(); form.set("username", "user"); form.set("password", "user"); - ResponseEntity entity = this.restTemplate.withRedirects(HttpRedirects.DONT_FOLLOW) - .exchange("/login", HttpMethod.POST, new HttpEntity<>(form, headers), String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - URI location = entity.getHeaders().getLocation(); + EntityExchangeResult result = nonFollowingRedirect().post() + .uri("/login") + .contentType(MediaType.APPLICATION_FORM_URLENCODED) + .accept(MediaType.TEXT_HTML) + .body(form) + .exchange() + .returnResult(String.class); + assertThat(result.getStatus()).isEqualTo(HttpStatus.FOUND); + URI location = result.getResponseHeaders().getLocation(); assertThat(location).isNotNull(); assertThat(location.toString()).endsWith(this.port + "/"); } diff --git a/smoke-test/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/AbstractErrorPageTests.java b/smoke-test/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/AbstractErrorPageTests.java index 86477b1ca83..4e2bb1983d2 100644 --- a/smoke-test/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/AbstractErrorPageTests.java +++ b/smoke-test/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/AbstractErrorPageTests.java @@ -20,12 +20,9 @@ import org.junit.jupiter.api.Test; import tools.jackson.databind.JsonNode; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @@ -37,11 +34,11 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient abstract class AbstractErrorPageTests { @Autowired - private TestRestTemplate testRestTemplate; + private RestTestClient client; private final String pathPrefix; @@ -51,58 +48,77 @@ abstract class AbstractErrorPageTests { @Test void testBadCredentials() { - final ResponseEntity response = this.testRestTemplate.withBasicAuth("username", "wrongpassword") - .exchange(this.pathPrefix + "/test", HttpMethod.GET, null, JsonNode.class); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); - JsonNode jsonResponse = response.getBody(); - assertThat(jsonResponse).isNull(); + this.client.get() + .uri(this.pathPrefix + "/test") + .headers((headers) -> headers.setBasicAuth("username", "wrongpassword")) + .exchange() + .expectStatus() + .isUnauthorized() + .expectBody(JsonNode.class) + .isEqualTo(null); } @Test void testNoCredentials() { - final ResponseEntity response = this.testRestTemplate.exchange(this.pathPrefix + "/test", - HttpMethod.GET, null, JsonNode.class); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); - JsonNode jsonResponse = response.getBody(); - assertThat(jsonResponse).isNull(); + this.client.get() + .uri(this.pathPrefix + "/test") + .exchange() + .expectStatus() + .isUnauthorized() + .expectBody(JsonNode.class) + .isEqualTo(null); } @Test void testPublicNotFoundPageWithCorrectCredentials() { - final ResponseEntity response = this.testRestTemplate.withBasicAuth("username", "password") - .exchange(this.pathPrefix + "/public/notfound", HttpMethod.GET, null, JsonNode.class); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); - JsonNode jsonResponse = response.getBody(); - assertThat(jsonResponse).isNotNull(); - assertThat(jsonResponse.get("error").asString()).isEqualTo("Not Found"); + this.client.get() + .uri(this.pathPrefix + "/public/notfound") + .headers((headers) -> headers.setBasicAuth("username", "password")) + .exchange() + .expectStatus() + .isNotFound() + .expectBody(JsonNode.class) + .value((body) -> { + assertThat(body).isNotNull(); + assertThat(body.get("error").asString()).isEqualTo("Not Found"); + }); } @Test void testPublicNotFoundPageWithBadCredentials() { - final ResponseEntity response = this.testRestTemplate.withBasicAuth("username", "wrong") - .exchange(this.pathPrefix + "/public/notfound", HttpMethod.GET, null, JsonNode.class); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); - JsonNode jsonResponse = response.getBody(); - assertThat(jsonResponse).isNull(); + this.client.get() + .uri(this.pathPrefix + "/public/notfound") + .headers((headers) -> headers.setBasicAuth("username", "wrong")) + .exchange() + .expectStatus() + .isUnauthorized() + .expectBody(JsonNode.class) + .isEqualTo(null); } @Test void testCorrectCredentialsWithControllerException() { - final ResponseEntity response = this.testRestTemplate.withBasicAuth("username", "password") - .exchange(this.pathPrefix + "/fail", HttpMethod.GET, null, JsonNode.class); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); - JsonNode jsonResponse = response.getBody(); - assertThat(jsonResponse).isNotNull(); - assertThat(jsonResponse.get("error").asString()).isEqualTo("Internal Server Error"); + this.client.get() + .uri(this.pathPrefix + "/fail") + .headers((headers) -> headers.setBasicAuth("username", "password")) + .exchange() + .expectStatus() + .is5xxServerError() + .expectBody(JsonNode.class) + .value((body) -> { + assertThat(body).isNotNull(); + assertThat(body.get("error").asString()).isEqualTo("Internal Server Error"); + }); } @Test void testCorrectCredentials() { - final ResponseEntity response = this.testRestTemplate.withBasicAuth("username", "password") - .exchange(this.pathPrefix + "/test", HttpMethod.GET, null, String.class); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); - response.getBody(); - assertThat(response.getBody()).isEqualTo("test"); + this.client.get() + .uri(this.pathPrefix + "/test") + .headers((headers) -> headers.setBasicAuth("username", "password")) + .exchangeSuccessfully() + .expectBody(String.class) + .isEqualTo("test"); } @Configuration(proxyBeanMethods = false) diff --git a/smoke-test/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/AbstractUnauthenticatedErrorPageTests.java b/smoke-test/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/AbstractUnauthenticatedErrorPageTests.java index 2299e6f4235..7e1898a812e 100644 --- a/smoke-test/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/AbstractUnauthenticatedErrorPageTests.java +++ b/smoke-test/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/AbstractUnauthenticatedErrorPageTests.java @@ -20,11 +20,8 @@ import org.junit.jupiter.api.Test; import tools.jackson.databind.JsonNode; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -34,11 +31,11 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient abstract class AbstractUnauthenticatedErrorPageTests { @Autowired - private TestRestTemplate testRestTemplate; + private RestTestClient rest; private final String pathPrefix; @@ -48,70 +45,100 @@ abstract class AbstractUnauthenticatedErrorPageTests { @Test void testBadCredentials() { - final ResponseEntity response = this.testRestTemplate.withBasicAuth("username", "wrongpassword") - .exchange(this.pathPrefix + "/test", HttpMethod.GET, null, JsonNode.class); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); - JsonNode jsonResponse = response.getBody(); - assertThat(jsonResponse).isNotNull(); - assertThat(jsonResponse.get("error").asString()).isEqualTo("Unauthorized"); + this.rest.get() + .uri(this.pathPrefix + "/test") + .headers((headers) -> headers.setBasicAuth("username", "wrongpassword")) + .exchange() + .expectStatus() + .isUnauthorized() + .expectBody(JsonNode.class) + .value((body) -> { + assertThat(body).isNotNull(); + assertThat(body.get("error").asString()).isEqualTo("Unauthorized"); + }); } @Test void testNoCredentials() { - final ResponseEntity response = this.testRestTemplate.exchange(this.pathPrefix + "/test", - HttpMethod.GET, null, JsonNode.class); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); - JsonNode jsonResponse = response.getBody(); - assertThat(jsonResponse).isNotNull(); - assertThat(jsonResponse.get("error").asString()).isEqualTo("Unauthorized"); + this.rest.get() + .uri(this.pathPrefix + "/test") + .exchange() + .expectStatus() + .isUnauthorized() + .expectBody(JsonNode.class) + .value((body) -> { + assertThat(body).isNotNull(); + assertThat(body.get("error").asString()).isEqualTo("Unauthorized"); + }); } @Test void testPublicNotFoundPage() { - final ResponseEntity response = this.testRestTemplate.exchange(this.pathPrefix + "/public/notfound", - HttpMethod.GET, null, JsonNode.class); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); - JsonNode jsonResponse = response.getBody(); - assertThat(jsonResponse).isNotNull(); - assertThat(jsonResponse.get("error").asString()).isEqualTo("Not Found"); + this.rest.get() + .uri(this.pathPrefix + "/public/notfound") + .exchange() + .expectStatus() + .isNotFound() + .expectBody(JsonNode.class) + .value((body) -> { + assertThat(body).isNotNull(); + assertThat(body.get("error").asString()).isEqualTo("Not Found"); + }); } @Test void testPublicNotFoundPageWithCorrectCredentials() { - final ResponseEntity response = this.testRestTemplate.withBasicAuth("username", "password") - .exchange(this.pathPrefix + "/public/notfound", HttpMethod.GET, null, JsonNode.class); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); - JsonNode jsonResponse = response.getBody(); - assertThat(jsonResponse).isNotNull(); - assertThat(jsonResponse.get("error").asString()).isEqualTo("Not Found"); + this.rest.get() + .uri(this.pathPrefix + "/public/notfound") + .headers((headers) -> headers.setBasicAuth("username", "password")) + .exchange() + .expectStatus() + .isNotFound() + .expectBody(JsonNode.class) + .value((body) -> { + assertThat(body).isNotNull(); + assertThat(body.get("error").asString()).isEqualTo("Not Found"); + }); } @Test void testPublicNotFoundPageWithBadCredentials() { - final ResponseEntity response = this.testRestTemplate.withBasicAuth("username", "wrong") - .exchange(this.pathPrefix + "/public/notfound", HttpMethod.GET, null, JsonNode.class); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); - JsonNode jsonResponse = response.getBody(); - assertThat(jsonResponse).isNotNull(); - assertThat(jsonResponse.get("error").asString()).isEqualTo("Unauthorized"); + this.rest.get() + .uri(this.pathPrefix + "/public/notfound") + .headers((headers) -> headers.setBasicAuth("username", "wrong")) + .exchange() + .expectStatus() + .isUnauthorized() + .expectBody(JsonNode.class) + .value((body) -> { + assertThat(body).isNotNull(); + assertThat(body.get("error").asString()).isEqualTo("Unauthorized"); + }); } @Test void testCorrectCredentialsWithControllerException() { - final ResponseEntity response = this.testRestTemplate.withBasicAuth("username", "password") - .exchange(this.pathPrefix + "/fail", HttpMethod.GET, null, JsonNode.class); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); - JsonNode jsonResponse = response.getBody(); - assertThat(jsonResponse).isNotNull(); - assertThat(jsonResponse.get("error").asString()).isEqualTo("Internal Server Error"); + this.rest.get() + .uri(this.pathPrefix + "/fail") + .headers((headers) -> headers.setBasicAuth("username", "password")) + .exchange() + .expectStatus() + .is5xxServerError() + .expectBody(JsonNode.class) + .value((body) -> { + assertThat(body).isNotNull(); + assertThat(body.get("error").asString()).isEqualTo("Internal Server Error"); + }); } @Test void testCorrectCredentials() { - final ResponseEntity response = this.testRestTemplate.withBasicAuth("username", "password") - .exchange(this.pathPrefix + "/test", HttpMethod.GET, null, String.class); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(response.getBody()).isEqualTo("test"); + this.rest.get() + .uri(this.pathPrefix + "/test") + .headers((headers) -> headers.setBasicAuth("username", "password")) + .exchangeSuccessfully() + .expectBody(String.class) + .isEqualTo("test"); } } diff --git a/smoke-test/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/SampleWebSecureApplicationTests.java b/smoke-test/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/SampleWebSecureApplicationTests.java index b0457604dab..781d02fed73 100644 --- a/smoke-test/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/SampleWebSecureApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/SampleWebSecureApplicationTests.java @@ -17,28 +17,26 @@ package smoketest.web.secure; import java.net.URI; -import java.util.Collections; import jakarta.servlet.DispatcherType; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.http.client.ClientHttpRequestFactoryBuilder; +import org.springframework.boot.http.client.HttpClientSettings; import org.springframework.boot.http.client.HttpRedirects; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.context.annotation.Bean; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer; import org.springframework.security.web.SecurityFilterChain; +import org.springframework.test.web.servlet.client.EntityExchangeResult; +import org.springframework.test.web.servlet.client.RestTestClient; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; @@ -53,49 +51,60 @@ import static org.springframework.security.config.Customizer.withDefaults; */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = { SampleWebSecureApplicationTests.SecurityConfiguration.class, SampleWebSecureApplication.class }) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleWebSecureApplicationTests { @Autowired - private TestRestTemplate restTemplate; + private RestTestClient rest; @LocalServerPort private int port; + private RestTestClient nonFollowingRedirect() { + return RestTestClient + .bindToServer(ClientHttpRequestFactoryBuilder.detect() + .build(HttpClientSettings.defaults().withRedirects(HttpRedirects.DONT_FOLLOW))) + .baseUrl("http://localhost:" + this.port) + .build(); + } + @Test void testHome() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Collections.singletonList(MediaType.TEXT_HTML)); - ResponseEntity entity = this.restTemplate.withRedirects(HttpRedirects.DONT_FOLLOW) - .exchange("/home", HttpMethod.GET, new HttpEntity<>(headers), String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - URI location = entity.getHeaders().getLocation(); + EntityExchangeResult result = nonFollowingRedirect().get() + .uri("/home") + .accept(MediaType.TEXT_HTML) + .exchange() + .returnResult(String.class); + assertThat(result.getStatus()).isEqualTo(HttpStatus.FOUND); + URI location = result.getResponseHeaders().getLocation(); assertThat(location).isNotNull(); assertThat(location.toString()).endsWith(this.port + "/login"); } @Test void testLoginPage() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Collections.singletonList(MediaType.TEXT_HTML)); - ResponseEntity entity = this.restTemplate.exchange("/login", HttpMethod.GET, new HttpEntity<>(headers), - String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("Login"); + this.rest.get() + .uri("/login") + .accept(MediaType.TEXT_HTML) + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("Login")); } @Test void testLogin() { - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Collections.singletonList(MediaType.TEXT_HTML)); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap form = new LinkedMultiValueMap<>(); form.set("username", "user"); form.set("password", "password"); - ResponseEntity entity = this.restTemplate.withRedirects(HttpRedirects.DONT_FOLLOW) - .exchange("/login", HttpMethod.POST, new HttpEntity<>(form, headers), String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - URI location = entity.getHeaders().getLocation(); + EntityExchangeResult result = nonFollowingRedirect().post() + .uri("/login") + .contentType(MediaType.APPLICATION_FORM_URLENCODED) + .accept(MediaType.TEXT_HTML) + .body(form) + .exchange() + .returnResult(String.class); + assertThat(result.getStatus()).isEqualTo(HttpStatus.FOUND); + URI location = result.getResponseHeaders().getLocation(); assertThat(location).isNotNull(); assertThat(location.toString()).endsWith(this.port + "/"); } diff --git a/smoke-test/spring-boot-smoke-test-web-static/src/test/java/smoketest/web/staticcontent/SampleWebStaticApplicationTests.java b/smoke-test/spring-boot-smoke-test-web-static/src/test/java/smoketest/web/staticcontent/SampleWebStaticApplicationTests.java index 76995f8cf23..13d68f7e822 100644 --- a/smoke-test/spring-boot-smoke-test-web-static/src/test/java/smoketest/web/staticcontent/SampleWebStaticApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-web-static/src/test/java/smoketest/web/staticcontent/SampleWebStaticApplicationTests.java @@ -19,13 +19,11 @@ package smoketest.web.staticcontent; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -35,26 +33,30 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleWebStaticApplicationTests { @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @Test void testHome() { - ResponseEntity entity = this.restTemplate.getForEntity("/", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("Static"); + this.restTestClient.get() + .uri("/") + .exchangeSuccessfully() + .expectBody(String.class) + .value((body) -> assertThat(body).contains("<title>Static")); } @Test void testCss() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/webjars/bootstrap/3.0.3/css/bootstrap.min.css", - String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("body"); - assertThat(entity.getHeaders().getContentType()).isEqualTo(MediaType.valueOf("text/css")); + this.restTestClient.get() + .uri("/webjars/bootstrap/3.0.3/css/bootstrap.min.css") + .exchangeSuccessfully() + .expectHeader() + .contentType(MediaType.valueOf("text/css")) + .expectBody(String.class) + .value((body) -> assertThat(body).contains("body")); } } diff --git a/smoke-test/spring-boot-smoke-test-web-thymeleaf/src/test/java/smoketest/web/thymeleaf/SampleWebUiApplicationTests.java b/smoke-test/spring-boot-smoke-test-web-thymeleaf/src/test/java/smoketest/web/thymeleaf/SampleWebUiApplicationTests.java index 27e478b7f11..8c21af9d78a 100644 --- a/smoke-test/spring-boot-smoke-test-web-thymeleaf/src/test/java/smoketest/web/thymeleaf/SampleWebUiApplicationTests.java +++ b/smoke-test/spring-boot-smoke-test-web-thymeleaf/src/test/java/smoketest/web/thymeleaf/SampleWebUiApplicationTests.java @@ -21,13 +21,11 @@ import java.net.URI; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.resttestclient.TestRestTemplate; -import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.client.RestTestClient; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; @@ -39,21 +37,21 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.http.clients.redirects=dont-follow") -@AutoConfigureTestRestTemplate +@AutoConfigureRestTestClient class SampleWebUiApplicationTests { @Autowired - private TestRestTemplate restTemplate; + private RestTestClient restTestClient; @LocalServerPort private int port; @Test void testHome() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("<title>Messages"); - assertThat(entity.getBody()).doesNotContain("layout:fragment"); + this.restTestClient.get().uri("/").exchangeSuccessfully().expectBody(String.class).value((body) -> { + assertThat(body).contains("<title>Messages"); + assertThat(body).doesNotContain("layout:fragment"); + }); } @Test @@ -61,7 +59,13 @@ class SampleWebUiApplicationTests { MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); map.set("text", "FOO text"); map.set("summary", "FOO"); - URI location = this.restTemplate.postForLocation("/", map); + URI location = this.restTestClient.post() + .uri("/") + .body(map) + .exchange() + .returnResult(Void.class) + .getResponseHeaders() + .getLocation(); assertThat(location).isNotNull(); assertThat(location.toString()).contains("localhost:" + this.port); } diff --git a/smoke-test/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/SampleWebFluxApplicationActuatorDifferentPortTests.java b/smoke-test/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/SampleWebFluxApplicationActuatorDifferentPortTests.java index bed7a5b4ad9..c11c51b1acd 100644 --- a/smoke-test/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/SampleWebFluxApplicationActuatorDifferentPortTests.java +++ b/smoke-test/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/SampleWebFluxApplicationActuatorDifferentPortTests.java @@ -18,11 +18,9 @@ package smoketest.webflux; import org.junit.jupiter.api.Test; -import org.springframework.boot.resttestclient.TestRestTemplate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalManagementPort; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.test.web.reactive.server.WebTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -41,10 +39,17 @@ class SampleWebFluxApplicationActuatorDifferentPortTests { @Test void linksEndpointShouldBeAvailable() { - ResponseEntity<String> entity = new TestRestTemplate("user", getPassword()) - .getForEntity("http://localhost:" + this.managementPort + "/", String.class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).contains("\"_links\""); + WebTestClient.bindToServer() + .baseUrl("http://localhost:" + this.managementPort) + .build() + .get() + .uri("/") + .headers((headers) -> headers.setBasicAuth("user", getPassword())) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value((response) -> assertThat(response).contains("\"_links\"")); } private String getPassword() {