2014-08-29 2 views
3

MockMvc와 JsonPath를 사용하여 Spring HATEOAS 백엔드의 단위 테스트를 작성하고 있습니다.Spring HATEOAS/MockMvc/JsonPath 모범 사례

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

이 자신을 쉽게 좋아하지만 내가 만들 때 사용하는 몇 가지 모범 사례가 있는지 궁금 :

  • 테스트를 내가 뭔가를하고 있어요 응답에 포함 된 링크를 테스트하려면 링크에 http://localhost이 포함되어 있다고 느끼지 않습니다. Spring MovkMvc 헬퍼를 사용하여 호스트를 결정할 수 있습니까?
  • JsonPath를 사용하면 배열에 2 개의 속성에 특정 값이있는 요소가 포함되어 있는지 테스트하기가 어렵습니다. 배열에 특정 값이있는 자체 링크가 있어야하는 것과 같습니다. 더 좋은 방법은 위의 것입니다. 이것은 오류 메시지가있는 필드에 대한 유효성 검사 오류를 테스트 할 때도 나타납니다.

나는했습니다 일부 블로그 게시물에서 아래와 같은 기술을 참조하십시오

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

하지만이 모든 제목에 특정 오류 메시지가왔다 보장하지 않습니다. 제목에 "설명의 최대 길이는 500 자입니다."라는 잘못 표시되어있을 수도 있습니다. 그러나 시험은 성공할 것이다.

답변

0

테스트시 링크를 통과하려면 Traverson (Spring HATEOAS에 포함)을 사용할 수 있습니다.

스프링 부트를 사용하는 경우 MockMvc이 아닌 @WebIntegrationTest("server.port=0")을 사용하는 것이 좋습니다. 일부 경우 실제 응용 프로그램과 약간 다른 동작을 경험했습니다.

내 게시물에 몇 가지 예가 있습니다. Implementing HAL hypermedia REST API using Spring HATEOAS. tests in the sample project도 확인하십시오.