Mar*_*ijk 6 rest spring spring-data-rest spring-hateoas
我正在使用MockMvc和JsonPath为Spring HATEOAS后端编写单元测试.要测试响应中包含的链接,我正在执行以下操作:
@Test
public void testListEmpty() throws Exception {
mockMvc.perform(get("/rest/customers"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.links", hasSize(1))) // make sure links only contains self link
.andExpect(jsonPath("$.links[?(@.rel=='self')]", hasSize(1))) // make sure the self link exists 1 time
.andExpect(jsonPath("$.links[?(@.rel=='self')].href", contains("http://localhost/rest/customers{?page,size,sort}"))) // test self link is correct
.andExpect(jsonPath("$.links[?(@.rel=='self')][0].href", is("http://localhost/rest/customers{?page,size,sort}"))) // alternative to test self link is correct
.andExpect(jsonPath("$.content", hasSize(0))); // make sure no content elements exists
}
Run Code Online (Sandbox Code Playgroud)
但是我想知道是否有一些最好的做法我应该用它来让自己更容易:
http://localhost
感觉不对.我可以使用一些Spring MovkMvc助手来确定主机吗?我在一些博文中看到了如下所示的技巧:
.andExpect(jsonPath("$.fieldErrors[*].path", containsInAnyOrder("title", "description")))
.andExpect(jsonPath("$.fieldErrors[*].message", containsInAnyOrder(
"The maximum length of the description is 500 characters.",
"The maximum length of the title is 100 characters.")));
Run Code Online (Sandbox Code Playgroud)
但这并不能保证标题具有特定的错误信息.也可能是标题错误地"描述的最大长度为500个字符".但测试会成功.
您可以使用Traverson
(包含在 Spring HATEOAS 中)来遍历测试中的链接。
如果您使用 Spring Boot,我会考虑使用@WebIntegrationTest("server.port=0")
而不是MockMvc
,因为在某些情况下我遇到的行为与实际应用程序略有不同。
您可能会在我的帖子中找到一些示例:Implementing HAL hypermedia REST API using Spring HATEOAS。另请查看示例项目中的测试。
归档时间: |
|
查看次数: |
2125 次 |
最近记录: |