Skip to content
Advertisement

Junit test with jsonPath doesn’t find the matching content

I have this simple unit test:-

@Test
void getCityName() throws Exception {
    when(weatherService.getWeatherByCity(capitalize(TestData.getWeather().getCity())))
            .thenReturn(TestData.getWeatherList());

 mockMvc.perform(get(WeatherController.WEATHER+WeatherController.GET_WEATHER_BY_CITY+"/espoo"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
    /*  it doesn't work if uncommented.  
            .andExpect(jsonPath("$.city")
                    .value("espoo"))
   */
            .andDo(MockMvcResultHandlers.print());

}

.andDo(MockMvcResultHandlers.print()); prints out this:-

    MockHttpServletResponse:
        Status = 200
    Error message = null
        Headers = [Content-Type:"application/json"]
    Content type = application/json
            Body = [{"id":null,"city":"espoo","country":null,"description":null,"currentTemp":0.0,"feelsLike":3.3,"minTemp":2.2,"maxTemp":5.5,"tempLimit":3.0,"frequency":5,"frequencyUnit":"SECOND","uri":"https://api.openweathermap.org/data/2.5/weather?q=espoo&units=metric&APPID=5536a9b0c84d081997982254c24fc53a"}]
    Forwarded URL = null
Redirected URL = null
        Cookies = []

I can see there is "city":"espoo". How do I match this. I tired:-

 .andExpect(jsonPath("$.city")
 .value("espoo"))

It give error:-

DEBUG org.springframework.test.web.servlet.TestDispatcherServlet – Completed 200 OK DEBUG com.jayway.jsonpath.internal.path.CompiledPath – Evaluating path: $.size() DEBUG com.jayway.jsonpath.internal.path.CompiledPath – Evaluating path: $[‘city’]

java.lang.AssertionError: No value at JSON path “$.city”

Advertisement

Answer

The response is of type Array:

[{"id":null,"city":"espoo","country":null,"description":null,"currentTemp":0.0,"feelsLike":3.3,"minTemp":2.2,"maxTemp":5.5,"tempLimit":3.0,"frequency":5,"frequencyUnit":"SECOND","uri":"https://api.openweathermap.org/data/2.5/weather?q=espoo&units=metric&APPID=5536a9b0c84d081997982254c24fc53a"}]

Therefore you will need to choose the index first, then attribute $[0].city

 .andExpect(jsonPath("$[0].city", is(espoo)))

=== Edited ===

Please try:

  .andExpect(jsonPath("$[0].city").value("espoo"));
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement