使用 jsonPath 的 Junit 测试找不到匹配的内容



我有一个简单的单元测试:-

@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());打印出这个:-

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 = []

我看到有"city":"espoo"。我该如何匹配这个。我累了:-

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

它给出错误:-

调试org.springframework.test.web.servlet.TestDispatcherServlet-已完成200 OK调试com.jayway.jsonpath.internal.path.CompiledPath-评估路径:$.size((调试com.jayway.jsonpath.internal.path.CompiledPath-评估路径:$['city']

java.lang.AssertionError:JSON路径"$"处没有值。城市;

响应类型为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"}]

因此,您需要首先选择索引,然后选择属性$[0].city

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

===已编辑===

请尝试:

.andExpect(jsonPath("$[0].city").value("espoo"));

相关内容

  • 没有找到相关文章

最新更新