Witam ponownie, staram się dochodzić do wprawy z testami. Wzorując sie na tym co mi podpowiedzieliście, książką i innymi https://phauer.com/2019/modern-best-practices-testing-java/
https://phauer.com/2019/focus-integration-tests-mock-based-tests/
tworzę testy integracyjne dla UserControllera.
Czy taki test jest akceptowalny :
@Test
void newUserCreated() throws Exception {
mockMvc.perform(post("/users/new")
.header(AUTHORIZATION, BEARER + obtainAccessToken(USER_ADMIN,ADMIN_PASSWORD))
.contentType(CONTENT_TYPE)
.content(NEW_USER_JSON)
.accept(CONTENT_TYPE))
.andExpect(status().isCreated())
.andExpect(content().string(containsString(USER_NEWUSER)));
}
czy może tak:
@Test
void newUserCreated() throws Exception {
MvcResult result = mockMvc.perform(post("/users/new")
.header(AUTHORIZATION, BEARER + obtainAccessToken(USER_ADMIN,ADMIN_PASSWORD))
.contentType(CONTENT_TYPE)
.content(NEW_USER_JSON)
.accept(CONTENT_TYPE))
.andExpect(status().isCreated())
.andReturn();
String responseJson = result.getResponse().getContentAsString();
assertThat(responseJson).contains("Krzys");
}
lub pełen test z wykorzystaniem serwisu:
@Test
void newUserCreated() throws Exception {
mockMvc.perform(post("/users/new")
.header(AUTHORIZATION, BEARER + obtainAccessToken(USER_ADMIN,ADMIN_PASSWORD))
.contentType(CONTENT_TYPE)
.content(NEW_USER_JSON)
.accept(CONTENT_TYPE))
.andExpect(status().isCreated())
.andExpect(content().string(containsString(userService.getUserByName(USER_NEWUSER).getName())));
}
albo w jakiś inny sposób taki test powinien być napisany ?
Który z tych testów jest najlepszy do tego ?
i jeszce jeden test, czy dobrze go napisałem?
@Test
void returnGoodValueOfUsers() throws Exception {
MvcResult result = mockMvc.perform(post("/users/all")
.header(AUTHORIZATION, BEARER + obtainAccessToken(USER_ADMIN, ADMIN_PASSWORD)))
.andExpect(status().isOk())
.andReturn();
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
List<User> userList = mapper.readValue(result.getResponse().getContentAsString(), new TypeReference<List<User>>() {});
assertThat(userList.size()).isEqualTo(2);
}