Created
March 15, 2021 22:42
-
-
Save josefigueredo/df9ae30658e3dff4886048957fa1436b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
e.g. for json path: https://github.com/json-path/JsonPath