'Check if object exists in array MockMvcResultMatchers
I'm writing tests using MockMvc in Spring. So I want to check if my response contains element I'm saving to repository, like so:
@Test
void getScreeningsShouldReturn200() throws Exception {
//given
Screening screening = Screening.createScreeningWithRoom(Movie.createMovieWithTitle("Interstellar"), ZonedDateTime.now().plusMinutes(240), Room.createRoom());
screeningRepository.save(screening);
List<Screening> screeningList = new ArrayList<>();
screeningList.add(screening);
System.out.println(mapper.writer().writeValueAsString(screening));
//TODO check below value if contains certain data
//when
mvc.perform(MockMvcRequestBuilders.get(url).contentType(MediaType.APPLICATION_JSON))
//then
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.content().string(mapper.writer().writeValueAsString(screeningList)))
.andReturn();
}
This way it works, but what if there would me many objects that I got from response, how would I find if this one exists inside array of many?
Thanks!
Solution 1:[1]
Use this code :
.andExpect(jsonPath("$.rootObjectName.listName[0].fieldName").exists())
And as a personal advice, do two tests :
- should_return_ok :
.andExpect(status().isOk()) - should_return_correct_data :
.andExpect(jsonPath("$.rootObjectName.listName[0].fieldName").value(<yourValue>))
- if you don't use result of
.andReturn();do implement it
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
