Loading...
Spring Framework Reference Documentation 7.0.2의 Defining Expectations의 한국어 번역본입니다.
아래의 경우에 피드백에서 신고해주신다면 반영하겠습니다.
감사합니다 :)
요청을 수행한 후 하나 이상의 andExpect(..) 호출을 추가함으로써 expectation을 정의할 수 있으며, 다음 예제와 같습니다. 하나의 expectation이 실패하는 즉시 다른 expectation들은 assert되지 않습니다.
1// static import of MockMvcRequestBuilders.* and MockMvcResultMatchers.* 2 3mockMvc.perform(get("/accounts/1")).andExpect(status().isOk());
1import org.springframework.test.web.servlet.get 2 3mockMvc.get("/accounts/1").andExpect { 4 status { isOk() } 5}
요청을 수행한 후 andExpectAll(..)을 추가함으로써 여러 expectation을 정의할 수 있으며, 다음 예제와 같습니다. andExpect(..)와는 대조적으로,
andExpectAll(..)은 제공된 모든 expectation이 assert되고 모든 실패가 추적 및 보고될 것을 보장합니다.
1// static import of MockMvcRequestBuilders.* and MockMvcResultMatchers.* 2 3mockMvc.perform(get("/accounts/1")).andExpectAll( 4 status().isOk(), 5 content().contentType("application/json;charset=UTF-8"));
1import org.springframework.test.web.servlet.get 2 3mockMvc.get("/accounts/1").andExpectAll { 4 status { isOk() } 5 content { contentType(APPLICATION_JSON) } 6}
MockMvcResultMatchers.*는 다수의 expectation을 제공하며, 그중 일부는 더 상세한 expectation으로 추가로 중첩됩니다.
Expectation은 일반적으로 두 가지 범주로 나뉩니다. 첫 번째 범주의 assertion은 response의 속성(예를 들어, response status, header, content)을 검증합니다.
이것들이 assert해야 할 가장 중요한 결과입니다.
두 번째 범주의 assertion은 response를 넘어서는 부분을 다룹니다. 이러한 assertion은 어떤 controller 메서드가 요청을 처리했는지, exception이 발생하여 처리되었는지, model의 content가 무엇인지, 어떤 view가 선택되었는지, 어떤 flash attribute가 추가되었는지 등을 검사할 수 있게 해 줍니다. 또한 request 및 session attribute와 같은 Servlet 특유의 측면도 검사할 수 있게 해 줍니다.
다음 test는 binding 또는 validation이 실패했음을 assert합니다:
1mockMvc.perform(post("/persons")) 2 .andExpect(status().isOk()) 3 .andExpect(model().attributeHasErrors("person"));
1import org.springframework.test.web.servlet.post 2 3mockMvc.post("/persons").andExpect { 4 status { isOk() } 5 model { 6 attributeHasErrors("person") 7 } 8}
test를 작성할 때, 수행된 요청의 결과를 dump하는 것이 유용한 경우가 많습니다. 다음과 같이 할 수 있으며, 여기서 print()는
MockMvcResultHandlers로부터의 static import입니다:
1mockMvc.perform(post("/persons")) 2 .andDo(print()) 3 .andExpect(status().isOk()) 4 .andExpect(model().attributeHasErrors("person"));
1import org.springframework.test.web.servlet.post 2 3mockMvc.post("/persons").andDo { 4 print() 5}.andExpect { 6 status { isOk() } 7 model { 8 attributeHasErrors("person") 9 } 10}
요청 처리에서 처리되지 않은 exception이 발생하지 않는 한, print() 메서드는 사용 가능한 모든 result data를 System.out에 출력합니다.
또한 log() 메서드와 print() 메서드의 두 가지 추가 variant가 있으며, 하나는 OutputStream을 받고 다른 하나는 Writer를 받습니다.
예를 들어, print(System.err)를 호출하면 result data를 System.err에 출력하고, print(myWriter)를 호출하면 result data를 custom writer에 출력합니다.
result data를 출력하는 대신 logging하고 싶다면, log() 메서드를 호출할 수 있으며, 이 메서드는 result data를
org.springframework.test.web.servlet.result logging category 아래의 단일 DEBUG message로 logging합니다.
경우에 따라 result에 직접 접근하여 다른 방법으로는 검증할 수 없는 내용을 검증하고 싶을 수 있습니다. 이는 다음 예제와 같이 다른 모든 expectation 뒤에
.andReturn()을 추가함으로써 달성할 수 있습니다:
1MvcResult mvcResult = mockMvc.perform(post("/persons")).andExpect(status().isOk()).andReturn(); 2// ...
1var mvcResult = mockMvc.post("/persons").andExpect { status { isOk() } }.andReturn() 2// ...
모든 test가 동일한 expectation을 반복한다면, 다음 예제와 같이 MockMvc 인스턴스를 build할 때 한 번만 공통 expectation을 설정할 수 있습니다:
1standaloneSetup(new SimpleController()) 2 .alwaysExpect(status().isOk()) 3 .alwaysExpect(content().contentType("application/json;charset=UTF-8")) 4 .build();
1standaloneSetup(SimpleController()) 2 .alwaysExpect<StandaloneMockMvcBuilder>(status().isOk()) 3 .alwaysExpect<StandaloneMockMvcBuilder>(content().contentType("application/json;charset=UTF-8")) 4 .build()
공통 expectation은 항상 적용되며 별도의 MockMvc 인스턴스를 생성하지 않고는 override할 수 없다는 점에 유의하십시오.
JSON response content에 Spring HATEOAS로 생성된 hypermedia link가 포함된 경우, 다음 예제와 같이 JsonPath expression을 사용하여 결과 link를 검증할 수 있습니다:
1mockMvc.perform(get("/people").accept(MediaType.APPLICATION_JSON)) 2 .andExpect(jsonPath("$.links[?(@.rel == 'self')].href").value("http://localhost:8080/people"));
1mockMvc.get("/people") { 2 accept(MediaType.APPLICATION_JSON) 3}.andExpect { 4 jsonPath("$.links[?(@.rel == 'self')].href") { 5 value("http://localhost:8080/people") 6 } 7}
XML response content에 Spring HATEOAS로 생성된 hypermedia link가 포함된 경우, XPath expression을 사용하여 결과 link를 검증할 수 있습니다:
1Map<String, String> ns = Collections.singletonMap("ns", "http://www.w3.org/2005/Atom"); 2mockMvc.perform(get("/handle").accept(MediaType.APPLICATION_XML)) 3 .andExpect(xpath("/person/ns:link[@rel='self']/@href", ns).string("http://localhost:8080/people"));
1val ns = mapOf("ns" to "http://www.w3.org/2005/Atom") 2mockMvc.get("/handle") { 3 accept(MediaType.APPLICATION_XML) 4}.andExpect { 5 xpath("/person/ns:link[@rel='self']/@href", ns) { 6 string("http://localhost:8080/people") 7 } 8}
Performing Requests
Async Requests