우리가 구현하지 않아도 스프링 웹 MVC에서 자동으로 처리하는 HTTP Method
HEAD
@Controller
public class SampleController {
@GetMapping("/hello", params = "name=spring")
@ResponseBody
public String hello(){
return "hello";
}
}
@RunWith(SpringRunner.class)
@WebMvcTest
public class SampleControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void helloTest() throws Exception{
mockMvc.perform(head("/hello")
.param("name", "spring"))
.andDo(print())
.andExpect(status().isOk());
}
}
OPTIONS
@Controller
public class SampleController {
@GetMapping("/hello")
@ResponseBody
public String hello(){
return "hello";
}
@PostMapping("/hello")
@ResponseBody
public String helloPost(){
return "hello";
}
}
@RunWith(SpringRunner.class)
@WebMvcTest
public class SampleControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void helloTest() throws Exception{
mockMvc.perform(options("/hello"))
.andDo(print())
.andExpect(status().isOk());
}
}
응답 Allow 헤더에 "GET, HEAD POST, OPTIONS"가 나온다.
테스트할 때 특정한 응답 헤더가 있는지 확인하고 싶으면 다음과 같이 한다.
@RunWith(SpringRunner.class)
@WebMvcTest
public class SampleControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void helloTest() throws Exception{
mockMvc.perform(options("/hello"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(header().exists(HttpHeaders.ALLOW));
}
}
응답 헤더의 값을 보고 싶으면 다음과 같이 작성한다.
@RunWith(SpringRunner.class)
@WebMvcTest
public class SampleControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void helloTest() throws Exception{
mockMvc.perform(options("/hello"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(header().stringValues(HttpHeaders.ALLOW, hasItems(
containsString("GET"),
containsString("POST"),
containsString("HEAD"),
containsString("OPTIONS")
)));
}
}
참고