Skip to content

Instantly share code, notes, and snippets.

@Cepr0
Last active August 16, 2022 16:05
Show Gist options
  • Save Cepr0/20547f192c22ef57248145666cbc2636 to your computer and use it in GitHub Desktop.
Save Cepr0/20547f192c22ef57248145666cbc2636 to your computer and use it in GitHub Desktop.
A variant of how to assert the response body in Spring MVC tests with AssertJ
@Autowired private ObjectMapper objectMapper;
@Autowired private MockMvc mockMvc;
@Test
public void create_when_all_is_correct_then_201_Created() throws Exception {
ResultActions result = mockMvc.perform(post(USERS)
.contentType(APPLICATION_JSON_UTF8)
.content(toJson(new UserRequest("user")))
.accept(APPLICATION_JSON)
);
result.andExpect(status().isCreated())
.andExpect(content().contentType(APPLICATION_JSON_UTF8));
// instead of this:
result
.andExpect(jsonPath("$.id", notNullValue()))
.andExpect(jsonPath("$.name", is("user")));
// we can do something like this:
var expected = new UserResponse("user");
assertBody(result, expected, "id") // ignore 'id' field
.satisfies(body -> assertThat(body.getId()).isNotNull()); // and check if it's not null
}
private <T> ObjectAssert<T> assertBody(ResultActions result, T expected, String... ignoredFields) throws Exception {
String body = result.andReturn().getResponse().getContentAsString();
//noinspection unchecked
return (ObjectAssert<T>) assertThat(objectMapper.readValue(body, expected.getClass()))
.isEqualToIgnoringGivenFields(expected, ignoredFields);
}
private String toJson(Object object) throws JsonProcessingException {
return objectMapper.writeValueAsString(object);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment