【问题标题】:Junit test with jsonPath doesn't find the matching content使用 jsonPath 进行 Junit 测试未找到匹配的内容
【发布时间】:2022-01-12 00:13:45
【问题描述】:

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

@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 路径“$.city”处没有值

【问题讨论】:

    标签: java junit5 jsonpath


    【解决方案1】:

    响应是数组类型:

    [{"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"));
    

    【讨论】:

    • 是的,它必须是正确的答案。但是当我累了.andExpect(jsonPath("$[0].city", is("espoo"))) 我得到编译器错误为“java:不兼容的类型:org.springframework.test.web.servlet.result.JsonPathResultMatchers 无法转换为 org.springframework.test.web.servlet.ResultMatcher”
    • 请看编辑@MasiBoo
    猜你喜欢
    • 2019-07-09
    • 2013-03-09
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    • 2018-05-22
    • 2011-01-20
    • 1970-01-01
    • 2021-10-25
    相关资源
    最近更新 更多