Spring Best Methods HATEOAS / MockMvc / JsonPath

I am writing unit tests for the Spring HATEOAS backed using MockMvc and JsonPath. To check the links contained in the answer, I do something like:

@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
}

      

However, I'm wondering if there are some best practices I should be using to make it easier for myself:

  • Test link contains http://localhost

    . Can I use some Spring MovkMvc helper to determine the host?
  • With JsonPath, it is difficult to check if an array contains an element that has 2 attributes with a specific value. Like an array must contain its own reference with a specific value. Is there a better way to test the above This will also take effect when testing validation errors for fields with error messages.

On some blogs I see a technique like below:

.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.")));

      

But this does not guarantee that the header has a specific error message. It may also be that the title is incorrectly specified "Maximum description length - 500 characters". but the test will succeed.

+3


source to share


1 answer


You can use Traverson

(included with Spring HATEOAS) to cross links in tests.

If you are using Spring Boot, I would consider using @WebIntegrationTest("server.port=0")

rather than MockMvc

, as in some cases I have experienced slightly different behavior from a real application.



You can find some example in my post: Implementing HAL Hyperlink REST API Using Spring HATEOAS . Also review the tests in the sample project .

0


source







All Articles