【问题标题】:Testing with spring-test-mvc jsonpath returns null使用 spring-test-mvc jsonpath 进行测试返回 null
【发布时间】:2012-11-01 23:28:25
【问题描述】:

我正在使用 Spring 的“spring-test-mvc”库来测试 Web 控制器。我有一个非常简单的控制器,它返回一个 JSON 数组。然后在我的测试中我有:

@Test
public void shouldGetAllUsersAsJson() throws Exception {
    mockMvc.perform(get("/v1/users").accept(MediaType.APPLICATION_JSON))
            .andExpect(content().mimeType(MediaType.APPLICATION_JSON))
            .andExpect(jsonPath("fName").exists());
}

以上测试返回:

java.lang.AssertionError: No value for JSON path: fName

为了快速检查我实际得到的结果,我运行了以下测试:

@Test
public void shouldPrintResults() throws Exception {
    mockMvc.perform(get("/v1/users").accept(MediaType.APPLICATION_JSON))
            .andDo(print());
}

它在MockHttpServletResponse的正文中返回正确的JSON数组

我不确定为什么 jsonPath 在 JSON 数组中看不到 fName

【问题讨论】:

    标签: spring mockito spring-test jsonpath spring-test-mvc


    【解决方案1】:

    您的 json 响应正文是什么样的?你可以通过.andDo(print())看到它

    你可能想试试jsonPath("$.fName")

    这是假设您的 json 响应是: {"fName":"first name"}

    如果您的响应是一个数组,那么您需要 jsonPath("$[0].fName") 来获得如下响应: [{"fName":"first name"},{"fName":"first name #2"}]

    您可以在以下位置查看更多示例:http://goessner.net/articles/JsonPath/

    【讨论】:

      【解决方案2】:

      如果你将 json 路径依赖添加到 maven,或者将 jar 添加到你的 lib,那么它将起作用。我认为 Spring 不包括最新 Spring 3.2.0 RC1 版本中的 jsonPath 依赖项。我猜这对于 Spring-Test-MVC 独立项目也是一样的。

      这里是 Maven 的依赖:

      <dependency>
          <groupId>com.jayway.jsonpath</groupId>
          <artifactId>json-path</artifactId>
          <version>0.8.1</version>
          <scope>test</scope>
      </dependency>
      

      您可能还需要 hamcrest 库来使用 jsonPath("$.test").value("test")

      <dependency>
          <groupId>org.hamcrest</groupId>
          <artifactId>hamcrest-library</artifactId>
          <version>1.3</version>
          <scope>test</scope>
      </dependency>
      

      【讨论】:

      • 我有这些依赖项。没有运气。同样的错误信息。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-21
      • 2013-05-16
      • 2012-05-25
      • 2017-07-28
      • 1970-01-01
      相关资源
      最近更新 更多