Spring HATEOAS/MockMvc/JsonPath最佳实践
我正在使用MockMvc和JsonPath为springhateoas后端编写单元测试。 要测试响应中包含的链接,我将执行以下操作:Spring HATEOAS/MockMvc/JsonPath最佳实践,spring,rest,spring-data-rest,spring-hateoas,Spring,Rest,Spring Data Rest,Spring Hateoas,我正在使用MockMvc和JsonPath为springhateoas后端编写单元测试。 要测试响应中包含的链接,我将执行以下操作: @Test public void testListEmpty() throws Exception { mockMvc.perform(get("/rest/customers")) .andExpect(status().isOk()) .andExpect(content().contentType(M
@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
}
然而,我想知道是否有一些最佳实践可以让我自己更容易做到,比如:
- 测试链接包含
感觉不对劲。我可以使用一些Spring-MovkMvc助手来确定主机吗http://localhost
- 使用JsonPath,很难测试数组是否包含两个属性具有特定值的元素。 这样,数组应该包含具有特定值的自链接。 有没有更好的方法来测试这一点 这在测试带有错误消息的字段的验证错误时也会起作用
.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.")));
但这并不能保证title有特定的错误消息。
也可能是标题中的“描述的最大长度为500个字符”错误。但是测试将成功。您可以使用
遍历(包含在Spring HATEOAS中)来遍历测试中的链接
如果使用Spring启动,我会考虑使用<代码> @ WebTimeTestTest[(Server .PoT=0)] < /C> >而不是<代码> MoCKMVC ,因为在某些情况下,我遇到的行为与实际应用略有不同。
你可以在我的帖子中找到一些例子:。
再看看这个 一种解决http://localhost
org.hamcrest.CoreMatchers.hasItem(org.hamcrest.Matcher nestedMatcher)
Matcher是在不牺牲测试数组元素上的两个属性约束的前提下使用的。上面显示的测试现在变为:
.andExpect(jsonPath("$.links[?(@.rel=='self')].href", hasItem(endsWith("/rest/customers{?page,size,sort}"))))
.andExpect(jsonPath("$.links[?(@.rel=='self')][0].href", hasItem(endsWith("/rest/customers{?page,size,sort}"))))