spring-mvc - 使用JSONPath和Spring MVC声明数组的数组

标签 spring-mvc junit jsonpath mockmvc

我很难弄清楚如何在spring mvc中的JSON文档响应中使用jsonPath断言。也许有比在此特定方案中使用jsonPath更好的方法来完成此操作。我想验证links数组是否具有“ self”的相关项,并且“ self”的对象的“ href”属性也具有等于“ /”的“ href”属性。 JSON响应如下所示:

 {  
   "links":[  
      {  
         "rel":[  
            "self"
         ],
         "href":"/"
      },
      {  
         "rel":[  
            "next"
         ],
         "href":"/1"
      }
   ]
}


我尝试了一下,可以看到它具有rel [0]拥有self,但是我宁愿不依赖于self所在的links数组和rel数组中的哪个位置,而是实际测试hrefs在links [rel] [self]上的含义是“ /”。
有任何想法吗?

 @Before
  public void setup() {
    MockitoAnnotations.initMocks(this);
    mockMvc = MockMvcBuilders.standaloneSetup(welcomeController).build();
  }

  @Test
  public void givenRootUrl_thenReturnLinkToSelf() throws Exception {
    mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
        .andExpect(jsonPath("$.links[0].rel[0].", is("self")));
  }

最佳答案

如何添加几个andExpect方法?类似于:

mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
    .andExpect(jsonPath("$.links[0].rel[0]", is("self")))
    .andExpect(jsonPath("$.links[0].href[0]", is("/"));

关于spring-mvc - 使用JSONPath和Spring MVC声明数组的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25614593/

相关文章:

Spring MVC 和虚拟主机处理

grails - 有没有办法在grails应用程序中添加第三方servlet?

java - 使用 Hibernate/JPA 映射和 JUnit 测试 DAO 的公式

java - 如何用camel编写jsonpath来选择json文件中的项目

java - Spring 3.0 MVC Controller 请求映射

java - Spring MVC Controller 没有返回正确的 View

android - 无法让 JUnit 测试在 Android Studio 中失败

unit-testing - 方法抛出 'org.mockito.exceptions.misusing.InvalidUseOfMatchersException' 异常。

kubernetes - 从 kubernetes pod 中获取环境变量并将其存储在数组中

amazon-web-services - AWS 步骤函数和可选参数