Spring测试–如何在jsonPath中测试JSON数组

在Spring,我们可以使用Hamcrest API(例如hasItemhasSize来测试JSON数组。 查看以下示例:

  1. package com.mkyong;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
  6. import org.springframework.boot.test.context.SpringBootTest;
  7. import org.springframework.boot.test.mock.mockito.MockBean;
  8. import org.springframework.http.HttpHeaders;
  9. import org.springframework.http.MediaType;
  10. import org.springframework.test.context.ActiveProfiles;
  11. import org.springframework.test.context.junit4.SpringRunner;
  12. import org.springframework.test.web.servlet.MockMvc;
  13. import static org.hamcrest.Matchers.*;
  14. import static org.mockito.ArgumentMatchers.any;
  15. import static org.mockito.Mockito.times;
  16. import static org.mockito.Mockito.verify;
  17. import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
  18. import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
  19. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
  20. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
  21. @RunWith(SpringRunner.class)
  22. @SpringBootTest
  23. @AutoConfigureMockMvc
  24. @ActiveProfiles("test")
  25. public class BookControllerTest {
  26. @Autowired
  27. private MockMvc mockMvc;
  28. @MockBean
  29. private BookRepository mockRepository;
  30. /*
  31. {
  32. "timestamp":"2019-03-05T09:34:13.280+0000",
  33. "status":400,
  34. "errors":["Author is not allowed.","Please provide a price","Please provide a author"]
  35. }
  36. */
  37. //article : jsonpath in array
  38. @Test
  39. public void save_emptyAuthor_emptyPrice_400() throws Exception {
  40. String bookInJson = "{\"name\":\"ABC\"}";
  41. mockMvc.perform(post("/books")
  42. .content(bookInJson)
  43. .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON))
  44. .andDo(print())
  45. .andExpect(status().isBadRequest())
  46. .andExpect(jsonPath("$.timestamp", is(notNullValue())))
  47. .andExpect(jsonPath("$.status", is(400)))
  48. .andExpect(jsonPath("$.errors").isArray())
  49. .andExpect(jsonPath("$.errors", hasSize(3)))
  50. .andExpect(jsonPath("$.errors", hasItem("Author is not allowed.")))
  51. .andExpect(jsonPath("$.errors", hasItem("Please provide a author")))
  52. .andExpect(jsonPath("$.errors", hasItem("Please provide a price")));
  53. verify(mockRepository, times(0)).save(any(Book.class));
  54. }
  55. }

PS已通过Spring Boot 2测试

参考文献

翻译自: https://mkyong.com/spring-boot/spring-test-how-to-test-a-json-array-in-jsonpath/

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值

举报

选择你想要举报的内容(必选)
  • 内容涉黄
  • 政治相关
  • 内容抄袭
  • 涉嫌广告
  • 内容侵权
  • 侮辱谩骂
  • 样式问题
  • 其他