Skip to content

Instantly share code, notes, and snippets.

@josefigueredo
Created March 15, 2021 22:42
Show Gist options
  • Save josefigueredo/df9ae30658e3dff4886048957fa1436b to your computer and use it in GitHub Desktop.
Save josefigueredo/df9ae30658e3dff4886048957fa1436b to your computer and use it in GitHub Desktop.
{
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));
// One way:
result
.andExpect(jsonPath("$.id", notNullValue()))
.andExpect(jsonPath("$.name", is("user")));
// Another:
var expected = new UserResponse("user");
assertBody(result, expected, "id") // ignore 'id' field
.satisfies(body -> assertThat(body.getId()).isNotNull());
}
// Helpers
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);
}
@josefigueredo
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment