Skip to content

Commit

Permalink
Migrate MockMvc tests to MockMvcTester
Browse files Browse the repository at this point in the history
  • Loading branch information
snicoll committed May 28, 2024
1 parent 58849dd commit 15cb487
Show file tree
Hide file tree
Showing 78 changed files with 979 additions and 1,260 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -54,15 +54,12 @@
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.filter.CompositeFilter;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;

/**
* Tests for {@link CloudFoundryActuatorAutoConfiguration}.
Expand Down Expand Up @@ -109,8 +106,8 @@ void cloudfoundryapplicationProducesActuatorMediaType() {
.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id",
"vcap.application.cf_api:https://my-cloud-controller.com")
.run((context) -> {
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
mockMvc.perform(get("/cloudfoundryapplication")).andExpect(header().string("Content-Type", V3_JSON));
MockMvcTester mvc = MockMvcTester.from(context);
assertThat(mvc.get().uri("/cloudfoundryapplication")).headers().hasValue("Content-Type", V3_JSON);
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
Expand All @@ -39,8 +40,6 @@
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName;
import static org.springframework.restdocs.request.RequestDocumentation.queryParameters;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
* Tests for generating documentation describing {@link AuditEventsEndpoint}.
Expand All @@ -53,13 +52,12 @@ class AuditEventsEndpointDocumentationTests extends MockMvcEndpointDocumentation
private AuditEventRepository repository;

@Test
void allAuditEvents() throws Exception {
void allAuditEvents() {
String queryTimestamp = "2017-11-07T09:37Z";
given(this.repository.find(any(), any(), any()))
.willReturn(List.of(new AuditEvent("alice", "logout", Collections.emptyMap())));
this.mockMvc.perform(get("/actuator/auditevents").param("after", queryTimestamp))
.andExpect(status().isOk())
.andDo(document("auditevents/all",
assertThat(this.mvc.get().uri("/actuator/auditevents").param("after", queryTimestamp)).hasStatusOk()
.apply(document("auditevents/all",
responseFields(fieldWithPath("events").description("An array of audit events."),
fieldWithPath("events.[].timestamp")
.description("The timestamp of when the event occurred."),
Expand All @@ -68,17 +66,18 @@ void allAuditEvents() throws Exception {
}

@Test
void filteredAuditEvents() throws Exception {
void filteredAuditEvents() {
OffsetDateTime now = OffsetDateTime.now();
String queryTimestamp = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(now);
given(this.repository.find("alice", now.toInstant(), "logout"))
.willReturn(List.of(new AuditEvent("alice", "logout", Collections.emptyMap())));
this.mockMvc
.perform(get("/actuator/auditevents").param("principal", "alice")
.param("after", queryTimestamp)
.param("type", "logout"))
.andExpect(status().isOk())
.andDo(document("auditevents/filtered",
assertThat(this.mvc.get()
.uri("/actuator/auditevents")
.param("principal", "alice")
.param("after", queryTimestamp)
.param("type", "logout"))
.hasStatusOk()
.apply(document("auditevents/filtered",
queryParameters(
parameterWithName("after").description(
"Restricts the events to those that occurred after the given time. Optional."),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,11 @@
import org.springframework.restdocs.payload.ResponseFieldsSnippet;
import org.springframework.util.CollectionUtils;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
* Tests for generating documentation describing {@link BeansEndpoint}.
Expand All @@ -48,7 +47,7 @@
class BeansEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {

@Test
void beans() throws Exception {
void beans() {
List<FieldDescriptor> beanFields = List.of(fieldWithPath("aliases").description("Names of any aliases."),
fieldWithPath("scope").description("Scope of the bean."),
fieldWithPath("type").description("Fully qualified type of the bean."),
Expand All @@ -60,9 +59,8 @@ void beans() throws Exception {
fieldWithPath("contexts").description("Application contexts keyed by id."), parentIdField(),
fieldWithPath("contexts.*.beans").description("Beans in the application context keyed by name."))
.andWithPrefix("contexts.*.beans.*.", beanFields);
this.mockMvc.perform(get("/actuator/beans"))
.andExpect(status().isOk())
.andDo(document("beans",
assertThat(this.mvc.get().uri("/actuator/beans")).hasStatusOk()
.apply(document("beans",
preprocessResponse(
limit(this::isIndependentBean, "contexts", getApplicationContext().getId(), "beans")),
responseFields));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,16 @@
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpStatus;
import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation;
import org.springframework.restdocs.payload.FieldDescriptor;
import org.springframework.restdocs.request.ParameterDescriptor;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName;
import static org.springframework.restdocs.request.RequestDocumentation.queryParameters;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
* Tests for generating documentation describing the {@link CachesEndpoint}
Expand All @@ -59,10 +58,9 @@ class CachesEndpointDocumentationTests extends MockMvcEndpointDocumentationTests
.optional());

@Test
void allCaches() throws Exception {
this.mockMvc.perform(get("/actuator/caches"))
.andExpect(status().isOk())
.andDo(MockMvcRestDocumentation.document("caches/all",
void allCaches() {
assertThat(this.mvc.get().uri("/actuator/caches")).hasStatusOk()
.apply(MockMvcRestDocumentation.document("caches/all",
responseFields(fieldWithPath("cacheManagers").description("Cache managers keyed by id."),
fieldWithPath("cacheManagers.*.caches")
.description("Caches in the application context keyed by name."))
Expand All @@ -71,25 +69,23 @@ void allCaches() throws Exception {
}

@Test
void namedCache() throws Exception {
this.mockMvc.perform(get("/actuator/caches/cities"))
.andExpect(status().isOk())
.andDo(MockMvcRestDocumentation.document("caches/named", queryParameters(queryParameters),
void namedCache() {
assertThat(this.mvc.get().uri("/actuator/caches/cities")).hasStatusOk()
.apply(MockMvcRestDocumentation.document("caches/named", queryParameters(queryParameters),
responseFields(levelFields)));
}

@Test
void evictAllCaches() throws Exception {
this.mockMvc.perform(delete("/actuator/caches"))
.andExpect(status().isNoContent())
.andDo(MockMvcRestDocumentation.document("caches/evict-all"));
void evictAllCaches() {
assertThat(this.mvc.delete().uri("/actuator/caches")).hasStatus(HttpStatus.NO_CONTENT)
.apply(MockMvcRestDocumentation.document("caches/evict-all"));
}

@Test
void evictNamedCache() throws Exception {
this.mockMvc.perform(delete("/actuator/caches/countries?cacheManager=anotherCacheManager"))
.andExpect(status().isNoContent())
.andDo(MockMvcRestDocumentation.document("caches/evict-named", queryParameters(queryParameters)));
void evictNamedCache() {
assertThat(this.mvc.delete().uri("/actuator/caches/countries?cacheManager=anotherCacheManager"))
.hasStatus(HttpStatus.NO_CONTENT)
.apply(MockMvcRestDocumentation.document("caches/evict-named", queryParameters(queryParameters)));
}

@Configuration(proxyBeanMethods = false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,10 @@
import org.springframework.restdocs.payload.FieldDescriptor;
import org.springframework.restdocs.payload.JsonFieldType;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
* Tests for generating documentation describing {@link ConditionsReportEndpoint}.
Expand Down Expand Up @@ -64,9 +63,8 @@ void conditions() throws Exception {
.optional());
FieldDescriptor unconditionalClassesField = fieldWithPath("contexts.*.unconditionalClasses")
.description("Names of unconditional auto-configuration classes if any.");
this.mockMvc.perform(get("/actuator/conditions"))
.andExpect(status().isOk())
.andDo(MockMvcRestDocumentation.document("conditions",
assertThat(this.mvc.get().uri("/actuator/conditions")).hasStatusOk()
.apply(MockMvcRestDocumentation.document("conditions",
preprocessResponse(limit("contexts", getApplicationContext().getId(), "positiveMatches"),
limit("contexts", getApplicationContext().getId(), "negativeMatches")),
responseFields(fieldWithPath("contexts").description("Application contexts keyed by id."))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -27,12 +27,11 @@
import org.springframework.context.annotation.Import;
import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.restdocs.payload.PayloadDocumentation.subsectionWithPath;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
* Tests for generating documentation describing
Expand All @@ -44,10 +43,9 @@
class ConfigurationPropertiesReportEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {

@Test
void configProps() throws Exception {
this.mockMvc.perform(get("/actuator/configprops"))
.andExpect(status().isOk())
.andDo(MockMvcRestDocumentation.document("configprops/all",
void configProps() {
assertThat(this.mvc.get().uri("/actuator/configprops")).hasStatusOk()
.apply(MockMvcRestDocumentation.document("configprops/all",
preprocessResponse(limit("contexts", getApplicationContext().getId(), "beans")),
responseFields(fieldWithPath("contexts").description("Application contexts keyed by id."),
fieldWithPath("contexts.*.beans.*")
Expand All @@ -62,10 +60,9 @@ void configProps() throws Exception {
}

@Test
void configPropsFilterByPrefix() throws Exception {
this.mockMvc.perform(get("/actuator/configprops/spring.jackson"))
.andExpect(status().isOk())
.andDo(MockMvcRestDocumentation.document("configprops/prefixed",
void configPropsFilterByPrefix() {
assertThat(this.mvc.get().uri("/actuator/configprops/spring.jackson")).hasStatusOk()
.apply(MockMvcRestDocumentation.document("configprops/prefixed",
preprocessResponse(limit("contexts", getApplicationContext().getId(), "beans")),
responseFields(fieldWithPath("contexts").description("Application contexts keyed by id."),
fieldWithPath("contexts.*.beans.*")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,12 @@
import org.springframework.restdocs.payload.FieldDescriptor;
import org.springframework.test.context.TestPropertySource;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.replacePattern;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
* Tests for generating documentation describing the {@link EnvironmentEndpoint}.
Expand All @@ -74,10 +73,9 @@ class EnvironmentEndpointDocumentationTests extends MockMvcEndpointDocumentation
.description("Name of the property source.");

@Test
void env() throws Exception {
this.mockMvc.perform(get("/actuator/env"))
.andExpect(status().isOk())
.andDo(document("env/all",
void env() {
assertThat(this.mvc.get().uri("/actuator/env")).hasStatusOk()
.apply(document("env/all",
preprocessResponse(
replacePattern(Pattern.compile(
"org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/"), ""),
Expand All @@ -93,10 +91,9 @@ void env() throws Exception {
}

@Test
void singlePropertyFromEnv() throws Exception {
this.mockMvc.perform(get("/actuator/env/com.example.cache.max-size"))
.andExpect(status().isOk())
.andDo(document("env/single",
void singlePropertyFromEnv() {
assertThat(this.mvc.get().uri("/actuator/env/com.example.cache.max-size")).hasStatusOk()
.apply(document("env/single",
preprocessResponse(replacePattern(Pattern
.compile("org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/"), "")),
responseFields(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,9 @@
import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation;
import org.springframework.restdocs.payload.FieldDescriptor;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
* Tests for generating documentation describing the {@link FlywayEndpoint}.
Expand All @@ -48,10 +47,9 @@
class FlywayEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {

@Test
void flyway() throws Exception {
this.mockMvc.perform(get("/actuator/flyway"))
.andExpect(status().isOk())
.andDo(MockMvcRestDocumentation.document("flyway",
void flyway() {
assertThat(this.mvc.get().uri("/actuator/flyway")).hasStatusOk()
.apply(MockMvcRestDocumentation.document("flyway",
responseFields(fieldWithPath("contexts").description("Application contexts keyed by id"),
fieldWithPath("contexts.*.flywayBeans.*.migrations")
.description("Migrations performed by the Flyway instance, keyed by Flyway bean name."))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,11 @@
import org.springframework.restdocs.payload.FieldDescriptor;
import org.springframework.util.unit.DataSize;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.restdocs.payload.PayloadDocumentation.subsectionWithPath;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
* Tests for generating documentation describing the {@link HealthEndpoint}.
Expand All @@ -72,7 +71,7 @@ class HealthEndpointDocumentationTests extends MockMvcEndpointDocumentationTests
subsectionWithPath("details").description("Details of the health of a specific part of the application."));

@Test
void health() throws Exception {
void health() {
FieldDescriptor status = fieldWithPath("status").description("Overall status of the application.");
FieldDescriptor components = fieldWithPath("components").description("The components that make up the health.");
FieldDescriptor componentStatus = fieldWithPath("components.*.status")
Expand All @@ -84,24 +83,21 @@ void health() throws Exception {
.description("Details of the health of a specific part of the application. "
+ "Presence is controlled by `management.endpoint.health.show-details`.")
.optional();
this.mockMvc.perform(get("/actuator/health").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(document("health",
assertThat(this.mvc.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON)).hasStatusOk()
.apply(document("health",
responseFields(status, components, componentStatus, nestedComponents, componentDetails)));
}

@Test
void healthComponent() throws Exception {
this.mockMvc.perform(get("/actuator/health/db").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(document("health/component", responseFields(componentFields)));
void healthComponent() {
assertThat(this.mvc.get().uri("/actuator/health/db").accept(MediaType.APPLICATION_JSON)).hasStatusOk()
.apply(document("health/component", responseFields(componentFields)));
}

@Test
void healthComponentInstance() throws Exception {
this.mockMvc.perform(get("/actuator/health/broker/us1").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(document("health/instance", responseFields(componentFields)));
void healthComponentInstance() {
assertThat(this.mvc.get().uri("/actuator/health/broker/us1").accept(MediaType.APPLICATION_JSON)).hasStatusOk()
.apply(document("health/instance", responseFields(componentFields)));
}

@Configuration(proxyBeanMethods = false)
Expand Down
Loading

0 comments on commit 15cb487

Please sign in to comment.