0

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"

1 Answer 1

1

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"));
Sign up to request clarification or add additional context in comments.

2 Comments

yes, it must the correct answer. But when I tired .andExpect(jsonPath("$[0].city", is("espoo"))) I got compiler error as "java: incompatible types: org.springframework.test.web.servlet.result.JsonPathResultMatchers cannot be converted to org.springframework.test.web.servlet.ResultMatcher"
Please see edit @MasiBoo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.