Skip to content

Commit ed67846

Browse files
committed
Use MockMvcTester where possible.
Migrated simple content, header, and status checks to AssertJ. Leaving more detailed JSON path evaluations as-is. See #2486
1 parent 3a6fdae commit ed67846

File tree

11 files changed

+217
-215
lines changed

11 files changed

+217
-215
lines changed

spring-data-rest-hal-explorer/src/test/java/org/springframework/data/rest/webmvc/halexplorer/HalExplorerIntegrationTests.java

Lines changed: 21 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,13 @@
1515
*/
1616
package org.springframework.data.rest.webmvc.halexplorer;
1717

18-
import static org.hamcrest.CoreMatchers.*;
18+
import static org.assertj.core.api.Assertions.*;
1919
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
20-
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
2120

2221
import org.junit.jupiter.api.BeforeEach;
2322
import org.junit.jupiter.api.Test;
2423
import org.junit.jupiter.api.extension.ExtendWith;
24+
2525
import org.springframework.beans.factory.annotation.Autowired;
2626
import org.springframework.context.annotation.Bean;
2727
import org.springframework.context.annotation.Configuration;
@@ -30,12 +30,12 @@
3030
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
3131
import org.springframework.hateoas.MediaTypes;
3232
import org.springframework.http.HttpHeaders;
33+
import org.springframework.http.HttpStatus;
3334
import org.springframework.http.MediaType;
3435
import org.springframework.test.context.ContextConfiguration;
3536
import org.springframework.test.context.junit.jupiter.SpringExtension;
3637
import org.springframework.test.context.web.WebAppConfiguration;
37-
import org.springframework.test.web.servlet.MockMvc;
38-
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
38+
import org.springframework.test.web.servlet.assertj.MockMvcTester;
3939
import org.springframework.web.context.WebApplicationContext;
4040
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
4141

@@ -67,51 +67,45 @@ RepositoryRestConfigurer configExtension() {
6767

6868
@Autowired WebApplicationContext context;
6969

70-
MockMvc mvc;
70+
MockMvcTester mvc;
7171

7272
@BeforeEach
7373
void setUp() {
74-
this.mvc = MockMvcBuilders.webAppContextSetup(context).//
75-
defaultRequest(get(BASE_PATH).accept(MediaType.TEXT_HTML)).build();
74+
mvc = MockMvcTester.from(context);
7675
}
7776

7877
@Test // DATAREST-293
79-
void exposesJsonUnderApiRootByDefault() throws Exception {
78+
void exposesJsonUnderApiRootByDefault() {
8079

81-
mvc.perform(get(BASE_PATH).accept(MediaType.ALL)).//
82-
andExpect(status().isOk()).//
83-
andExpect(header().string(HttpHeaders.CONTENT_TYPE, startsWith(MediaTypes.VND_HAL_JSON.toString())));
80+
assertThat(mvc.perform(get(BASE_PATH).accept(MediaType.ALL))).hasStatusOk().hasHeader(HttpHeaders.CONTENT_TYPE,
81+
MediaTypes.VND_HAL_JSON.toString());
8482
}
8583

8684
@Test // DATAREST-293
87-
void redirectsToBrowserForApiRootAndHtml() throws Exception {
85+
void redirectsToBrowserForApiRootAndHtml() {
8886

89-
mvc.perform(get(BASE_PATH).accept(MediaType.TEXT_HTML)).//
90-
andExpect(status().isFound()).//
91-
andExpect(header().string(HttpHeaders.LOCATION, endsWith(TARGET)));
87+
assertThat(mvc.perform(get(BASE_PATH).accept(MediaType.TEXT_HTML))).hasStatus(HttpStatus.FOUND)
88+
.hasHeader(HttpHeaders.LOCATION, "http://localhost" + TARGET);
9289
}
9390

9491
@Test // DATAREST-293
95-
void forwardsBrowserToIndexHtml() throws Exception {
92+
void forwardsBrowserToIndexHtml() {
9693

97-
mvc.perform(get(BASE_PATH.concat("/explorer"))).//
98-
andExpect(status().isFound()).//
99-
andExpect(header().string(HttpHeaders.LOCATION, endsWith(TARGET)));
94+
assertThat(mvc.perform(get(BASE_PATH.concat("/explorer")))).hasStatus(HttpStatus.FOUND)
95+
.hasHeader(HttpHeaders.LOCATION, "http://localhost" + TARGET);
10096
}
10197

10298
@Test // DATAREST-293
103-
void exposesHalBrowser() throws Exception {
99+
void exposesHalBrowser() {
104100

105-
mvc.perform(get(BASE_PATH.concat("/explorer/index.html"))).//
106-
andExpect(status().isOk()).//
107-
andExpect(content().string(containsString("HAL Explorer")));
101+
assertThat(mvc.perform(get(BASE_PATH.concat("/explorer/index.html")))).hasStatusOk().bodyText()
102+
.contains("HAL Explorer");
108103
}
109104

110105
@Test // DATAREST-293
111-
void retrunsApiIfHtmlIsNotExplicitlyListed() throws Exception {
106+
void retrunsApiIfHtmlIsNotExplicitlyListed() {
112107

113-
mvc.perform(get(BASE_PATH).accept(MediaType.APPLICATION_JSON, MediaType.ALL)).//
114-
andExpect(status().isOk()).//
115-
andExpect(header().string(HttpHeaders.CONTENT_TYPE, startsWith(MediaType.APPLICATION_JSON_VALUE)));
108+
assertThat(mvc.perform(get(BASE_PATH).accept(MediaType.APPLICATION_JSON, MediaType.ALL))).hasStatusOk()
109+
.hasHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
116110
}
117111
}

spring-data-rest-tests/spring-data-rest-tests-core/src/test/java/org/springframework/data/rest/tests/AbstractWebIntegrationTests.java

Lines changed: 32 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,7 @@
1616
package org.springframework.data.rest.tests;
1717

1818
import static org.assertj.core.api.Assertions.*;
19-
import static org.hamcrest.CoreMatchers.*;
2019
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
21-
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
2220

2321
import io.micrometer.observation.ObservationRegistry;
2422
import jakarta.servlet.Filter;
@@ -37,12 +35,15 @@
3735

3836
import org.junit.jupiter.api.BeforeEach;
3937
import org.junit.jupiter.api.extension.ExtendWith;
38+
4039
import org.springframework.beans.factory.annotation.Autowired;
4140
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
4241
import org.springframework.hateoas.Link;
4342
import org.springframework.hateoas.LinkRelation;
4443
import org.springframework.hateoas.client.LinkDiscoverers;
44+
import org.springframework.http.HttpHeaders;
4545
import org.springframework.http.HttpMethod;
46+
import org.springframework.http.HttpStatus;
4647
import org.springframework.http.MediaType;
4748
import org.springframework.http.server.observation.ServerRequestObservationContext;
4849
import org.springframework.mock.web.MockHttpServletResponse;
@@ -51,6 +52,8 @@
5152
import org.springframework.test.context.web.WebAppConfiguration;
5253
import org.springframework.test.web.servlet.MockMvc;
5354
import org.springframework.test.web.servlet.ResultMatcher;
55+
import org.springframework.test.web.servlet.assertj.MockMvcTester;
56+
import org.springframework.test.web.servlet.assertj.MvcTestResult;
5457
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
5558
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
5659
import org.springframework.util.LinkedMultiValueMap;
@@ -84,48 +87,48 @@ public abstract class AbstractWebIntegrationTests {
8487
@Autowired LinkDiscoverers discoverers;
8588

8689
protected TestMvcClient client;
87-
protected MockMvc mvc;
90+
protected MockMvc mockMvc;
91+
protected MockMvcTester mvc;
8892
protected ServerRequestObservationContext observationContext;
8993

9094
@BeforeEach
9195
public void setUp() {
9296
setupMockMvc();
93-
this.client = new TestMvcClient(mvc, discoverers);
97+
this.client = new TestMvcClient(mockMvc, discoverers);
9498
}
9599

96100
protected void setupMockMvc() {
97-
this.mvc = MockMvcBuilders.webAppContextSetup(context) //
101+
this.mockMvc = MockMvcBuilders.webAppContextSetup(context) //
98102
.defaultRequest(get("/").accept(TestMvcClient.DEFAULT_MEDIA_TYPE)) //
99103
.addFilters(new FilterImplementation()) //
100104
.build();
105+
this.mvc = MockMvcTester.create(mockMvc);
101106
}
102107

103108
protected MockHttpServletResponse postAndGet(Link link, Object payload, MediaType mediaType) throws Exception {
104109

105110
String href = link.isTemplated() ? link.expand().getHref() : link.getHref();
106111

107-
MockHttpServletResponse response = mvc.perform(post(href).content(payload.toString()).contentType(mediaType))//
108-
.andExpect(status().isCreated())//
109-
.andExpect(header().string("Location", is(notNullValue())))//
110-
.andReturn().getResponse();
112+
MvcTestResult result = mvc.perform(post(href).content(payload.toString()).contentType(mediaType));
113+
assertThat(result).hasStatus(HttpStatus.CREATED).headers().containsHeader(HttpHeaders.LOCATION);
111114

112-
String content = response.getContentAsString();
115+
String content = result.getResponse().getContentAsString();
113116

114117
if (StringUtils.hasText(content)) {
115-
return response;
118+
return result.getResponse();
116119
}
117120

118-
return client.request(response.getHeader("Location"));
121+
return client.request(result.getResponse().getHeader("Location"));
119122
}
120123

121124
protected MockHttpServletResponse putAndGet(Link link, Object payload, MediaType mediaType) throws Exception {
122125

123126
String href = link.isTemplated() ? link.expand().getHref() : link.getHref();
124127

125-
MockHttpServletResponse response = mvc.perform(put(href).content(payload.toString()).contentType(mediaType))//
126-
.andExpect(status().is2xxSuccessful())//
127-
.andReturn().getResponse();
128+
MvcTestResult result = mvc.perform(put(href).content(payload.toString()).contentType(mediaType));
129+
assertThat(result).hasStatus2xxSuccessful();
128130

131+
MockHttpServletResponse response = result.getResponse();
129132
return StringUtils.hasText(response.getContentAsString()) ? response : client.request(link);
130133
}
131134

@@ -134,9 +137,10 @@ protected MockHttpServletResponse putOnlyExpect5XXStatus(Link link, Object paylo
134137

135138
String href = link.isTemplated() ? link.expand().getHref() : link.getHref();
136139

137-
MockHttpServletResponse response = mvc.perform(put(href).content(payload.toString()).contentType(mediaType))//
138-
.andExpect(status().is5xxServerError())//
139-
.andReturn().getResponse();
140+
MvcTestResult result = mvc.perform(put(href).content(payload.toString()).contentType(mediaType));
141+
assertThat(result).hasStatus5xxServerError();
142+
143+
MockHttpServletResponse response = result.getResponse();
140144

141145
return StringUtils.hasText(response.getContentAsString()) ? response : client.request(link);
142146
}
@@ -145,9 +149,11 @@ protected MockHttpServletResponse patchAndGet(Link link, Object payload, MediaTy
145149

146150
String href = link.isTemplated() ? link.expand().getHref() : link.getHref();
147151

148-
MockHttpServletResponse response = mvc.perform(MockMvcRequestBuilders.request(HttpMethod.PATCH, href).//
149-
content(payload.toString()).contentType(mediaType)).andExpect(status().is2xxSuccessful())//
150-
.andReturn().getResponse();
152+
MvcTestResult result = mvc.perform(MockMvcRequestBuilders.request(HttpMethod.PATCH, href).//
153+
content(payload.toString()).contentType(mediaType));
154+
assertThat(result).hasStatus2xxSuccessful();
155+
156+
MockHttpServletResponse response = result.getResponse();
151157

152158
return StringUtils.hasText(response.getContentAsString()) ? response : client.request(href);
153159
}
@@ -156,13 +162,13 @@ protected void deleteAndVerify(Link link) throws Exception {
156162

157163
String href = link.isTemplated() ? link.expand().getHref() : link.getHref();
158164

159-
mvc.perform(delete(href))//
160-
.andExpect(status().isNoContent())//
161-
.andReturn().getResponse();
165+
MvcTestResult result = mvc.perform(delete(href));
166+
assertThat(result).hasStatus(HttpStatus.NO_CONTENT);
167+
168+
MockHttpServletResponse response = result.getResponse();
162169

163170
// Check that the resource is unavailable after a DELETE
164-
mvc.perform(get(href))//
165-
.andExpect(status().isNotFound());
171+
assertThat(mvc.perform(get(href))).hasStatus(HttpStatus.NOT_FOUND);//
166172
}
167173

168174
protected Link assertHasContentLinkWithRel(LinkRelation relation, MockHttpServletResponse response) throws Exception {

spring-data-rest-tests/spring-data-rest-tests-core/src/test/java/org/springframework/data/rest/tests/CommonWebTests.java

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
import java.util.Map;
2929

3030
import org.junit.jupiter.api.Test;
31-
import org.springframework.data.rest.webmvc.RestMediaTypes;
31+
3232
import org.springframework.hateoas.IanaLinkRelations;
3333
import org.springframework.hateoas.Link;
3434
import org.springframework.hateoas.LinkRelation;
@@ -60,7 +60,8 @@ public abstract class CommonWebTests extends AbstractWebIntegrationTests {
6060
@Test
6161
void exposesRootResource() throws Exception {
6262

63-
ResultActions actions = mvc.perform(get("/").accept(TestMvcClient.DEFAULT_MEDIA_TYPE)).andExpect(status().isOk());
63+
ResultActions actions = mockMvc.perform(get("/").accept(TestMvcClient.DEFAULT_MEDIA_TYPE))
64+
.andExpect(status().isOk());
6465

6566
for (LinkRelation rel : expectedRootLinkRels()) {
6667
actions.andExpect(client.hasLinkWithRel(rel));
@@ -85,7 +86,8 @@ void exposesSchemasForResourcesExposed() throws Exception {
8586
client.follow(profileLink).andExpect(status().is2xxSuccessful());
8687

8788
// JSON Schema
88-
client.follow(profileLink, RestMediaTypes.SCHEMA_JSON).andExpect(status().is2xxSuccessful());
89+
client.follow(profileLink, org.springframework.data.rest.webmvc.RestMediaTypes.SCHEMA_JSON)
90+
.andExpect(status().is2xxSuccessful());
8991

9092
// ALPS
9193
client.follow(profileLink, MediaTypes.ALPS_JSON).andExpect(status().is2xxSuccessful());
@@ -95,15 +97,15 @@ void exposesSchemasForResourcesExposed() throws Exception {
9597
@Test // DATAREST-203
9698
void servesHalWhenRequested() throws Exception {
9799

98-
mvc.perform(get("/")). //
100+
mockMvc.perform(get("/")). //
99101
andExpect(content().contentTypeCompatibleWith(MediaTypes.HAL_JSON)). //
100102
andExpect(jsonPath("$._links", notNullValue()));
101103
}
102104

103105
@Test // DATAREST-203
104106
void servesHalWhenJsonIsRequested() throws Exception {
105107

106-
mvc.perform(get("/").accept(MediaType.APPLICATION_JSON)). //
108+
mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)). //
107109
andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)). //
108110
andExpect(jsonPath("$._links", notNullValue()));
109111
}
@@ -125,8 +127,8 @@ void exposesSearchesForRootResources() throws Exception {
125127
try {
126128

127129
client.follow(it).//
128-
andExpect(client.hasLinkWithRel(IanaLinkRelations.SELF)).//
129-
andExpect(jsonPath("$.domainType").doesNotExist());
130+
andExpect(client.hasLinkWithRel(IanaLinkRelations.SELF)).//
131+
andExpect(jsonPath("$.domainType").doesNotExist());
130132

131133
} catch (Exception e) {
132134
throw new RuntimeException(e);
@@ -156,7 +158,7 @@ void nic() throws Exception {
156158
content(payload).//
157159
contentType(MediaType.APPLICATION_JSON);
158160

159-
mvc.perform(request). //
161+
mockMvc.perform(request). //
160162
andExpect(status().isCreated());
161163
}
162164
}
@@ -196,7 +198,7 @@ void exposesDescriptionAsAlpsDocuments() throws Exception {
196198
MockHttpServletResponse response = client.request("/");
197199
Link profileLink = client.assertHasLinkWithRel(LinkRelation.of("profile"), response);
198200

199-
mvc.perform(//
201+
mockMvc.perform(//
200202
get(profileLink.expand().getHref()).//
201203
accept(ALPS_MEDIA_TYPE))
202204
.//
@@ -207,7 +209,7 @@ void exposesDescriptionAsAlpsDocuments() throws Exception {
207209
@Test // DATAREST-448
208210
void returnsNotFoundForUriNotBackedByARepository() throws Exception {
209211

210-
mvc.perform(get("/index.html")).//
212+
mockMvc.perform(get("/index.html")).//
211213
andExpect(status().isNotFound());
212214
}
213215

@@ -218,7 +220,7 @@ void collectionResourcesExposeLinksAsHeadersForHeadRequest() throws Exception {
218220

219221
Link link = client.discoverUnique(rel);
220222

221-
MockHttpServletResponse response = mvc.perform(head(link.expand().getHref()))//
223+
MockHttpServletResponse response = mockMvc.perform(head(link.expand().getHref()))//
222224
.andExpect(status().isNoContent())//
223225
.andReturn().getResponse();
224226

@@ -241,12 +243,12 @@ void patchToNonExistingResourceReturnsNotFound() throws Exception {
241243

242244
// Try to find non existing resource
243245
uri = uri.concat(id);
244-
status = mvc.perform(get(URI.create(uri))).andReturn().getResponse().getStatus();
246+
status = mockMvc.perform(get(URI.create(uri))).andReturn().getResponse().getStatus();
245247

246248
} while (status != HttpStatus.NOT_FOUND.value());
247249

248250
// PATCH to non-existing resource
249-
mvc.perform(patch(URI.create(uri))).andExpect(status().isNotFound());
251+
mockMvc.perform(patch(URI.create(uri))).andExpect(status().isNotFound());
250252
}
251253

252254
@Test // DATAREST-1003
@@ -256,7 +258,7 @@ void rejectsUnsupportedAcceptTypeForResources() throws Exception {
256258

257259
Link link = client.discoverUnique(string);
258260

259-
mvc.perform(get(link.expand().getHref())//
261+
mockMvc.perform(get(link.expand().getHref())//
260262
.accept(MediaType.valueOf("application/schema+json")))//
261263
.andExpect(status().isNotAcceptable());
262264
}

0 commit comments

Comments
 (0)