Skip to content

Commit 359733d

Browse files
committed
Assert content type after having checked the response status
1 parent 42b1fed commit 359733d

File tree

1 file changed

+8
-18
lines changed

1 file changed

+8
-18
lines changed

core/src/main/java/com/cosium/hal_mock_mvc/Templates.java

Lines changed: 8 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package com.cosium.hal_mock_mvc;
22

3+
import static com.cosium.hal_mock_mvc.OrMatcher.anyOf;
34
import static java.util.Objects.requireNonNull;
45
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
6+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
57

68
import com.fasterxml.jackson.annotation.JsonCreator;
79
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -14,8 +16,6 @@
1416
import java.util.Optional;
1517
import java.util.stream.Collectors;
1618
import org.springframework.hateoas.MediaTypes;
17-
import org.springframework.mock.web.MockHttpServletResponse;
18-
import org.springframework.test.web.servlet.MvcResult;
1919
import org.springframework.test.web.servlet.ResultActions;
2020

2121
/**
@@ -30,27 +30,17 @@ public class Templates {
3030
Templates(RequestExecutor requestExecutor, ResultActions resultActions) throws Exception {
3131
this.requestExecutor = requireNonNull(requestExecutor);
3232

33-
resultActions.andExpect(content().contentType(MediaTypes.HAL_FORMS_JSON));
33+
resultActions
34+
.andExpect(anyOf(status().is2xxSuccessful(), status().is3xxRedirection()))
35+
.andExpect(content().contentType(MediaTypes.HAL_FORMS_JSON));
3436

35-
MvcResult mvcResult = resultActions.andReturn();
36-
MockHttpServletResponse response = mvcResult.getResponse();
37-
int responseStatus = response.getStatus();
38-
String jsonBody = response.getContentAsString();
39-
if (responseStatus < 200 || responseStatus >= 400) {
40-
throw new IllegalStateException(
41-
"GET on "
42-
+ mvcResult.getRequest().getRequestURI()
43-
+ " failed with code "
44-
+ responseStatus
45-
+ " and body '"
46-
+ jsonBody
47-
+ "'");
48-
}
4937
objectMapper =
5038
new ObjectMapper()
5139
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
5240
.registerModule(new JacksonModule());
53-
body = objectMapper.readValue(jsonBody, HalFormsBody.class);
41+
body =
42+
objectMapper.readValue(
43+
resultActions.andReturn().getResponse().getContentAsString(), HalFormsBody.class);
5444
}
5545

5646
public Optional<Template> byOptionalKey(String key) {

0 commit comments

Comments
 (0)